var appFormly = angular.module('formlyExample', [
    'formly', 'formlyBootstrap', 'ui.bootstrap',
    'ngSanitize', 'ui.select', 'ui.grid'
]);
app.requires.push('formlyExample');
// var appFormly = angular.module('formlyExample', [
//     'formly', 'formlyBootstrap','ui.bootstrap',
//     'ngSanitize','ui.select','ui.grid'],
appFormly.config(
    function config(formlyConfigProvider) {
        //格式转换方法 XXX-XXX转驼峰命名
        function camelize(string) {
            string = string.replace(/[\-_\s]+(.)?/g, function(match, chr) {
                return chr ? chr.toUpperCase() : '';
            });
            // Ensure 1st char is always lowercase
            return string.replace(/^([A-Z])/, function(match, chr) {
                return chr ? chr.toLowerCase() : '';
            });
        }
        //获取ngModelAttr对象设置
        function getNgModelAttr(attrs, bindings) {
            var ngModelAttrs = {};
            angular.forEach(attrs, function(attr) {
                ngModelAttrs[camelize(attr)] = { attribute: attr };
            });

            angular.forEach(bindings, function(binding) {
                ngModelAttrs[camelize(binding)] = { bound: binding };
            });
            return ngModelAttrs;
        }

        formlyConfigProvider.setWrapper({
            name: 'bootstrapLabel',
            templateUrl: 'assets/views/customform/tpl/normal-label.html'
        });

        formlyConfigProvider.setType({
            name: 'ui-panel',
            templateUrl: 'assets/views/customform/tpl/ui-panel.html'
        });

        formlyConfigProvider.setType({
            name: 'ui-currentuser',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-username.html',
            controller: ['$scope', function($scope) {
                if ($scope.options.templateOptions.user) {
                    $scope.model[$scope.options.key] = $scope.options.templateOptions.user;
                    $scope.options.initialValue = $scope.model[$scope.options.key];
                }
            }]
        });

        //重构组件模板
        //只读控件
        formlyConfigProvider.setType({
            name: 'ui-label',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-label.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        translate: '',
                        refreshDelay: 0
                    }
                }
            },
            controller: ['$scope', function($scope) {
                var value = $scope.model[$scope.options.key];

                function treeDesc(children, key, label) {
                    if (label == "") {
                        label = children[key];
                    } else {
                        label = children[key] + "-" + label;
                    }
                    if (angular.isDefined(children.parent)) {
                        treeDesc(children.parent, key, label);
                    } else {
                        return label;
                    }
                }
                if (angular.isArray(value)) {
                    var tempValue = "";
                    angular.forEach(value, function(item) {
                        if (tempValue != "") {
                            tempValue = tempValue + ",";
                        }
                        tempValue = tempValue + item[$scope.options.templateOptions.labelProp] || item;
                    });
                    $scope.options.templateOptions.translate = tempValue;
                } else if (angular.isObject(value)) {
                    if (angular.isDefined(value.children) || angular.isDefined(value.parent)) {
                        //tree
                        // console.log("value.parent="+JSON.stringify(value.parent))
                        var nameLabel = value[$scope.options.templateOptions.labelProp];
                        nameLabel = treeDesc(value.parent, $scope.options.templateOptions.labelProp, nameLabel);
                        $scope.options.templateOptions.translate = nameLabel;
                    } else {
                        $scope.options.templateOptions.translate = value;
                    }

                } else if (angular.isString(value) && value.indexOf('yyyy-MM-ddTHH:mm:sssZ') > 0) {
                    console.log("value=" + value);
                    $scope.options.templateOptions.translate = value;
                } else {
                    // console.log("$scope.options.templateOptions.translate="+JSON.stringify($scope.options.templateOptions.translate))
                    $scope.options.templateOptions.translate = value;
                }
                if (angular.isFunction($scope.options.templateOptions.transform)) {
                    // console.log("$scope.options.templateOptions.transform22="+JSON.stringify($scope.options.templateOptions.transform))
                    $scope.options.templateOptions.translate = $scope.options.templateOptions.transform($scope.originalModel, value);
                }

            }]
        });


        //标题组件
        formlyConfigProvider.setType({
            name: 'ui-title',
            template: '<section id="page-title-form"><div class="row"><div class="col-sm-8"><h1 class="mainTitle" style="font-weight:bold">{{options.templateOptions.label}}</h1><span class="mainDescription">{{options.templateOptions.placeholder}}</span></div></div></section>'
        });
        //按钮组
        formlyConfigProvider.setType({
            name: 'ui-button',
            templateUrl: 'assets/views/customform/tpl/ui-button.html',
            defaultOptions: function(options) {
                return {
                    noFormControl: true
                }
            }
        });
        //3d组link
        formlyConfigProvider.setType({
            name: 'ui-link',
            templateUrl: 'assets/views/customform/tpl/ui-link.html',
            defaultOptions: function(options) {
                return {
                    noFormControl: true
                }
            }
        });

        //隐藏域组件
        formlyConfigProvider.setType({
            name: 'ui-hidden',
            extends: 'input',
            template: '<input type="text" ng-model="model[options.key]" style="display: none;"/ >',
            defaultOptions: function(options) {
                return {
                    //                noFormControl: true
                };
            }
        });
        //文本框组件
        formlyConfigProvider.setType({
            name: 'ui-input',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-input.html',
            defaultOptions: function(options) {
                return {};
            }
        });
        //只读文本
        formlyConfigProvider.setType({
            name: 'ui-disableinput',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-disableinput.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        transform: function(value) {
                            var ret = "";
                            if (value) {
                                ret = "已删除";
                            } else {
                                ret = "正常";
                            }
                            return ret;
                        }
                    }
                };
            }
        });
        formlyConfigProvider.setType({
            name: 'ui-disinput',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-disinput.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {

                    }
                };
            }
        });
        //数字组件
        formlyConfigProvider.setType({
            name: 'ui-number',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-number.html',
            defaultOptions: function(options) {
                return {};
            }
        });



        //下拉框组件
        formlyConfigProvider.setType({
            name: 'ui-select',
            extends: 'select',
            templateUrl: 'assets/views/customform/tpl/ui-select.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refresh: function() {},
                        refreshDelay: 0,
                        linkage: function(modelName, data, model, modelKey, key) {
                            angular.extend(data, { "idx": 0, "sum": 1 });
                            options.templateOptions.APIService.fetchDataList(modelName, data).then(function(response) {
                                var myData = options.templateOptions.Restangular.stripRestangular(response);
                                var list = myData.list;
                                if (list.length == 1) {
                                    angular.forEach(model.$parent.fields, function(item) {
                                        if (item.templateOptions.pkey == modelKey + "." + key) {
                                            item.value(list[0][key][item.key]);
                                        }
                                    })
                                }
                            });
                        }
                    }
                };
            }
        });
        //下拉多选框组件
        formlyConfigProvider.setType({
            name: 'ui-multiselect',
            extends: 'select',
            templateUrl: 'assets/views/customform/tpl/ui-multiselect.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refresh: function() {},
                        refreshDelay: 0
                    }
                };
            },
            controller: ['$scope', function($scope) {
                $scope.model[$scope.options.key] = [];
            }]
        });

        //下拉多选框灵活组件
        formlyConfigProvider.setType({
            name: 'ui-multiselectplus',
            extends: 'select',
            templateUrl: 'assets/views/customform/tpl/ui-multiselectplus.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refreshData: function(search, options, model, that) {
                            var process = options.templateOptions.ApiService.all("");
                            if (search) {

                            } else {

                            }
                            var postData = options.templateOptions.optionsPostData;
                            if (angular.isFunction(options.templateOptions.optionsPostData)) {
                                postData = options.templateOptions.optionsPostData(options, model, that);
                            }
                            process.customPOST(postData, options.templateOptions.optionsUrl).then(function(result) {
                                if (!options.templateOptions.options) {
                                    options.templateOptions.options = [];
                                }
                                if (options.templateOptions.optionsDataKey) {
                                    options.templateOptions.options = result[options.templateOptions.optionsDataKey];
                                } else {
                                    options.templateOptions.options = result;
                                }
                                if (options.templateOptions.optionsChecked) {
                                    options.value(options.templateOptions.options);
                                }
                            });
                        },
                        refreshDelay: 0
                    }
                };
            },
            controller: ['$scope', function($scope) {
                if (angular.isArray($scope.model[$scope.options.key])) {

                } else {
                    $scope.model[$scope.options.key] = [];
                }
            }]

        });

        //多选下拉框组件
        formlyConfigProvider.setType({
            name: 'ui-multi-select-tree',
            extends: 'multiCheckbox',
            templateUrl: 'assets/views/customform/tpl/ui-multi-select-tree.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refresh: function(items) {
                            //console.log(items);
                            function convertListToTree(data, treeMap) {
                                var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
                                var root = null; //Initially set our loop to null

                                //loop over data
                                for (var i = 0; i < data.length; i++) {
                                    var datum = data[i];
                                    //each node will have children, so let's give it a "children" poperty
                                    datum.children = [];

                                    //add an entry for this node to the map so that any future children can
                                    //lookup the parent
                                    idToNodeMap[datum.id] = datum;

                                    //Does this node have a parent?
                                    // console.log("datum="+JSON.stringify(datum))

                                    if (typeof datum.parent === "undefined") {

                                        //Doesn't look like it, so this node is the root of the tree
                                        root = datum;
                                        treeMap[i] = root;

                                    } else {

                                        //This node has a parent, so let's look it up using the id
                                        parentNode = idToNodeMap[datum.parent.id];

                                        //We don't need this property, so let's delete it.
                                        delete datum.parent;

                                        //Let's add the current node as a child of the parent node.
                                        parentNode.children.push(datum);

                                    }
                                }
                                return root;
                            }

                            function convertParentToChildList(data) {
                                // console.log("data="+JSON.stringify(data))
                                var treeMap = {};
                                var list = [];
                                convertListToTree(data, treeMap);
                                angular.forEach(treeMap, function(item) {
                                    // console.log("item="+JSON.stringify(item))
                                    list.push(item);
                                });
                                return list;
                            }

                            function selectItem(pmodel, childrens) {
                                if (angular.isArray(pmodel)) {

                                } else {
                                    if (pmodel && pmodel.id) {
                                        angular.forEach(childrens, function(item) {
                                            if (item.id == pmodel.id) {
                                                item.selected = true;
                                            }
                                            if (item && item.children) {
                                                selectItem(pmodel, item.children);
                                            }
                                        });
                                    }
                                }
                            }

                            options.templateOptions.refreshData(options.templateOptions.APIService).then(function(result) {
                                if (!options.templateOptions.options) {
                                    options.templateOptions.options = [];
                                }
                                if (options.templateOptions.optionsDataKey) {
                                    options.templateOptions.options = convertParentToChildList(result[options.templateOptions.optionsDataKey]);
                                } else {
                                    options.templateOptions.options = convertParentToChildList(result);
                                }

                                //set default value
                                var pmodel, i = 0;
                                if (options.templateOptions.pkey) {
                                    if (options.templateOptions.pkey.indexOf(".") > 0) {
                                        angular.forEach(options.templateOptions.pkey.split("."), function(p) {
                                            if (i == 0) {
                                                if (options.model[p] == null) {
                                                    options.model[p] = {};
                                                }
                                                pmodel = options.model[p];
                                                i++;
                                            } else {
                                                if (pmodel[p] == null) {
                                                    pmodel[p] = {};
                                                }
                                                pmodel = pmodel[p];
                                            }
                                        });
                                    } else {
                                        pmodel = options.model[options.templateOptions.pkey];
                                    }
                                }
                                if (pmodel) {
                                    pmodel = pmodel[options.key];
                                } else {
                                    pmodel = options.model[options.key];
                                }
                                if (pmodel && pmodel.id) {
                                    selectItem(pmodel, options.templateOptions.options);
                                }

                                items.inputModel = options.templateOptions.options;
                            });
                        }
                    },
                    // $scope.onChange(model[options.key], options, this, $event ,model){validators.required.expression()}
                    validators: {
                        required: {
                            expression: function(viewValue, modelValue) {
                                var value = modelValue || viewValue;
                                if (angular.isArray(value)) {
                                    return value.length > 0
                                } else if (angular.isUndefined(value.id)) {
                                    return value = "";
                                } else {
                                    return value != null;
                                }
                            }
                        }
                    }
                }
            },
            controller: ['$scope', function($scope) {

                if ($scope.options.templateOptions.isMultiSelect) {

                } else {
                    if ($scope.model[$scope.options.key]) {}
                }
                //$scope.model[$scope.options.key]=[];
            }]
        });
        //勾选组件
        formlyConfigProvider.setType({
            name: 'ui-checkbox',
            extends: 'checkbox',
            templateUrl: 'assets/views/customform/tpl/ui-checkbox.html'
        });
        //多选框组件
        formlyConfigProvider.setType({
            name: 'ui-checklist',
            extends: 'multiCheckbox',
            templateUrl: 'assets/views/customform/tpl/ui-checklist.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refresh: function() {},
                        refreshDelay: 0
                    }
                };
            }
        });
        //单选框组件
        formlyConfigProvider.setType({
            name: 'ui-radio',
            extends: 'radio',
            templateUrl: 'assets/views/customform/tpl/ui-radio.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refresh: function() {},
                        refreshDelay: 0
                    }
                };
            }
        });


        //文本域组件
        formlyConfigProvider.setWrapper({
            name: 'validation',
            types: ['ui-textarea'],
            template: "<formly-transclude></formly-transclude><div class=\"has-error\" ng-messages=\"fc.$error\" ng-if=\"options.formControl.$touched\"><div class=\"error\" ng-message=\"{{::name}}\" ng-repeat=\"(name, message) in ::options.validation.messages\">{{message(fc.$viewValue, fc.$modelValue, this)}}</div></div>"
        });

        formlyConfigProvider.setType({
            name: 'ui-textarea',
            extends: 'textarea',
            templateUrl: 'assets/views/customform/tpl/ui-textarea.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        transform: function(model, value) {
                            return value;
                        },
                    },
                    validation: {
                        messages: {
                            maxlength: function(viewValue, modelValue, scope) {
                                if (viewValue != null) {
                                    if (viewValue.length > scope.to.maxlength) {
                                        return scope.to.label + ' 字数(' + viewValue.length + ')超限(' + scope.to.maxlength + ')'
                                    } else {
                                        return "";
                                    }
                                }
                            },
                            // disable: function(){
                            //     return disabled;
                            // }
                        }
                    }
                }
            },
            controller: ['$scope', function($scope) {
                var value = $scope.model[$scope.options.key];
                if (angular.isFunction($scope.options.templateOptions.transform)) {
                    $scope.model[$scope.options.key] = $scope.options.templateOptions.transform($scope.originalModel, value);
                }
            }]
        });


        //文本框自定义选择面板组件
        formlyConfigProvider.setType({
            name: 'ui-input-selectmodal',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-input-selectmodal.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        openModal: function(size, options, modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/modal-content.html',
                                controller: 'ModalInstanceCtrl', //'CustomformCtrl',//
                                size: size,
                                resolve: options.templateOptions.modalParam
                            });
                            modalInstance.result.then(function(selectedItem) {
                                options.value(selectedItem);
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            }
        });
        //日期控件
        var datepicker_attr = [
            'date-disabled',
            'custom-class',
            'show-weeks',
            'starting-day',
            'init-date',
            'min-mode',
            'max-mode',
            'format-day',
            'format-month',
            'format-year',
            'format-day-header',
            'format-day-title',
            'format-month-title',
            'year-range',
            'shortcut-propagation',
            'datepicker-popup',
            'show-button-bar',
            'current-text',
            'clear-text',
            'close-text',
            'close-on-date-selection',
            'datepicker-append-to-body'
        ];
        var datepicker_bindings = [
            'datepicker-mode',
            'min-date',
            'max-date'
        ];

        formlyConfigProvider.setType({
            name: 'ui-datetime',
            templateUrl: 'assets/views/customform/tpl/ui-datetime.html',
            extends: 'input',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions: {
                ngModelAttrs: getNgModelAttr(datepicker_attr, datepicker_bindings),
                templateOptions: {
                    datepickerPopup: 'yyyy-MM-dd HH:mm:ss'
                }
            },
            controller: ['$scope', '$filter', function($scope, $filter) {
                $scope.model[$scope.options.key] = $filter('date')(new Date(), $scope.options.templateOptions.datepickerPopup);
                $scope.options.initialValue = $scope.model[$scope.options.key];
            }]
        });
        //日期控件
        formlyConfigProvider.setType({
            name: 'ui-datepicker',
            templateUrl: 'assets/views/customform/tpl/ui-datepicker.html',
            extends: 'input',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions: {
                ngModelAttrs: getNgModelAttr(datepicker_attr, datepicker_bindings),
                templateOptions: {
                    datepickerPopup: 'yyyy-MM-dd HH:mm:ss'
                }
            },
            controller: ['$scope', '$filter', function($scope, $filter) {
                $scope.model[$scope.options.key] = $filter('date')(new Date(), $scope.options.templateOptions.datepickerPopup);
                $scope.options.initialValue = $scope.model[$scope.options.key];
                $scope.endOpen = true;
                $scope.datepicker = {};
                $scope.datepicker.opened = false;
                $scope.datepicker.open = function($event) {
                    $scope.datepicker.opened = true;
                };
            }]
        });

        formlyConfigProvider.setType({
            name: "ui-disrequester",
            templateUrl: 'assets/views/customform/tpl/ui-disrequester.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions: function(options) {
                return {
                    templateOptions: {}
                };
            },
            controller: ['$scope', function($scope) {
                $scope.options.templateOptions.that = $scope;
            }]
        });

        //用户单选控件
        formlyConfigProvider.setType({
            name: "ui-requesterselect",
            templateUrl: 'assets/views/customform/tpl/ui-requester.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        openModal: function(size, options, modal) {
                            var modelObject = options.value();

                            var searchModal = function(filterSearchData) {
                                var modalInstance = modal.open({
                                    templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                    controller: function($scope, i18nService, $modalInstance, items, title, Restangular, APIService, language, searchData) {
                                        $scope.langs = i18nService.getAllLangs();
                                        $scope.lang = 'zh-cn';
                                        i18nService.setCurrentLang($scope.lang);
                                        $scope.gridOptions = {};
                                        $scope.gridOptions.data = 'myData';
                                        $scope.gridOptions.enableColumnResizing = true;
                                        $scope.gridOptions.enableFiltering = false;
                                        $scope.gridOptions.enableGridMenu = false;
                                        $scope.gridOptions.showGridFooter = true;
                                        $scope.gridOptions.showColumnFooter = true;
                                        $scope.gridOptions.fastWatch = true;
                                        $scope.gridOptions.useExternalPagination = true;
                                        $scope.gridOptions.paginationPageSizes = [10];
                                        $scope.gridOptions.paginationPageSize = 10;
                                        $scope.gridOptions.multiSelect = false;

                                        $scope.gridOptions.rowIdentity = function(row) {
                                            return row.id;
                                        };
                                        $scope.gridOptions.getRowIdentity = function(row) {
                                            return row.id;
                                        };
                                        //{"id":1,"phone":"15071189091","name":"管理员","gender":"男","flag":1,"email":"asda@qq.com","account":"000001","group":[{"id":3,"groupName":"运行监控科"}]}
                                        $scope.gridOptions.columnDefs = [
                                            { name: 'account', displayName: '账号', width: 140 },
                                            { name: 'name', displayName: '名称', width: 100 },
                                            { name: 'gender', displayName: '性别', width: 140 },
                                            { name: 'mphone', displayName: '电话', width: 100 },
                                            { name: 'email', displayName: '邮件', width: 100 },
                                            { name: 'dept.dept', displayName: '部门', width: 100 },
                                            { name: 'group[0].groupName', displayName: '角色', width: 100 }
                                        ];

                                        $scope.gridOptions.onRegisterApi = function(gridApi) {
                                            $scope.gridApi = gridApi;
                                            gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
                                                $scope.loadData({ "idx": newPage - 1, "sum": pageSize });
                                            });

                                            gridApi.selection.on.rowSelectionChanged($scope, function(data) {
                                                if (angular.isDefined(data.entity.account) && data.entity.account.length == 6) {
                                                    $scope.selected.item = data.entity;
                                                } else { alert("请求人账号格式不对，账号应为6位数，请重新填写！") }
                                            });
                                        };

                                        $scope.loadData = function(filterData) {
                                            items.fetchItems(filterData, APIService).then(function(data) {
                                                var myData = Restangular.stripRestangular(data);
                                                $scope.gridOptions.totalItems = myData.totalNum;
                                                $scope.myData = myData.list;
                                            });
                                        };
                                        $scope.title = title;
                                        if (searchData) {
                                            $scope.loadData(searchData);
                                        } else {
                                            $scope.loadData({
                                                idx: 0,
                                                sum: 10
                                            });
                                        }


                                        $scope.selected = {
                                            item: {}
                                        };

                                        $scope.ok = function() {
                                            $modalInstance.close($scope.selected.item);
                                        };

                                        $scope.cancel = function() {
                                            $modalInstance.dismiss('cancel');
                                        };
                                    },
                                    size: size,
                                    resolve: {
                                        items: function() {
                                            return {
                                                fetchItems: function(filterData, APIService) {
                                                    filterData = filterData || {};
                                                    if (angular.isUndefined(filterData.idx) || filterData.idx == null) {
                                                        filterData = {
                                                            idx: 0,
                                                            sum: 10
                                                        };
                                                    }
                                                    return options.templateOptions.fetchItems(filterData, APIService);
                                                }
                                            };
                                        },
                                        title: function() {
                                            return options.templateOptions.modalTitle;
                                        },
                                        Restangular: function() {
                                            return options.templateOptions.Restangular;
                                        },
                                        APIService: function() {
                                            return options.templateOptions.ApiService;
                                        },
                                        language: function() {
                                            return options.templateOptions.language;
                                        },
                                        searchData: function() {
                                            return filterSearchData;
                                        }
                                    }
                                });
                                modalInstance.result.then(function(selectedItem) {
                                    options.value(selectedItem);
                                    if (options.templateOptions.callback && angular.isFunction(options.templateOptions.callback)) {
                                        options.templateOptions.callback(selectedItem, options);
                                    }
                                }, function() {
                                    //console.log('Modal dismissed at: ' + new Date());
                                });
                            }
                            if (modelObject != null && angular.isDefined(modelObject.account)) {
                                var searchAccount = modelObject.account;
                                if (searchAccount.length == 6) {
                                    var filterData = {
                                        'requester': {
                                            'account': searchAccount
                                        },
                                        idx: 0,
                                        sum: 10
                                    };
                                    options.templateOptions.ApiService.fetchDataList('requester', filterData).then(function(data) {
                                        var myData = options.templateOptions.Restangular.stripRestangular(data);
                                        if (myData.list.length >= 1) {
                                            if (myData.list.length == 1) {
                                                options.value(myData.list[0]);
                                            } else {
                                                searchModal(filterData);
                                            }
                                        } else {
                                            searchModal();
                                        }
                                    });
                                } else {
                                    searchModal();
                                }
                            } else {
                                searchModal();
                            }
                        },
                        addRequeter: function(size, options, modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/modal-add-requester.html',
                                controller: function($scope, $modalInstance, items, title, Restangular, APIService, UserService) {
                                    $scope.title = "新增请求人";

                                    $scope.requester = {

                                    };

                                    $scope.refreshDepts = function(key) {
                                        var filterData = {
                                            'idx': 0,
                                            'sum': 10,
                                            'dept': {
                                                'name': key
                                            }
                                        };
                                        UserService.fetchDataList('department', filterData).then(function(response) {
                                            if (response.status == 200) {
                                                $scope.depts = response.list;
                                            }
                                        })
                                    }

                                    $scope.ok = function() {
                                        $modalInstance.close($scope.requester);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return {
                                            fetchItems: function(filterData, APIService) {
                                                filterData = filterData || {};
                                                if (!filterData.idx) {
                                                    filterData = {
                                                        idx: 0,
                                                        sum: 10
                                                    };
                                                }
                                                return options.templateOptions.fetchItems(filterData, APIService);
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular: function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    UserService: function() {
                                        return options.templateOptions.UserService;
                                    }
                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                if (selectedItem) {
                                    var data = {
                                        'requester': selectedItem
                                    };
                                    options.templateOptions.UserService.addData('requester', data).then(function(response) {
                                        if (response.status == 200) {
                                            options.value(response.data);
                                        }
                                    })
                                }
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            },
            controller: ['$scope', function($scope) {
                $scope.options.templateOptions.that = $scope;
            }]
        });



        //用户单选控件
        formlyConfigProvider.setType({
            name: "ui-userselect",
            templateUrl: 'assets/views/customform/tpl/ui-userselect.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        openModal: function(size, options, modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                controller: function($scope, i18nService, $modalInstance, items, title, Restangular, APIService, onDataCallback, parentScope) {
                                    $scope.langs = i18nService.getAllLangs();
                                    $scope.lang = 'zh-cn';
                                    i18nService.setCurrentLang($scope.lang);
                                    $scope.gridOptions = {};
                                    $scope.gridOptions.data = 'myData';
                                    $scope.gridOptions.enableColumnResizing = true;
                                    $scope.gridOptions.enableFiltering = true;
                                    $scope.gridOptions.enableGridMenu = false;
                                    $scope.gridOptions.showGridFooter = true;
                                    $scope.gridOptions.showColumnFooter = true;
                                    $scope.gridOptions.fastWatch = true;
                                    $scope.gridOptions.useExternalFiltering = true;
                                    $scope.gridOptions.useExternalPagination = true;
                                    $scope.gridOptions.paginationPageSizes = [10];
                                    $scope.gridOptions.paginationPageSize = 10;
                                    $scope.gridOptions.multiSelect = false;

                                    $scope.gridOptions.rowIdentity = function(row) {
                                        return row.id;
                                    };
                                    $scope.gridOptions.getRowIdentity = function(row) {
                                        return row.id;
                                    };
                                    //{"id":1,"phone":"15071189091","name":"管理员","gender":"男","flag":1,"email":"asda@qq.com","account":"000001","group":[{"id":3,"groupName":"运行监控科"}]}
                                    $scope.gridOptions.columnDefs = [
                                        // { name:'id', width:80, enableFiltering:false},
                                        { name: 'account', displayName: '工号', width: 140 },
                                        { name: 'name', displayName: '名称', width: 100 },
                                        { name: 'gender', displayName: '性别', width: 140, enableFiltering: false },
                                        { name: 'phone', displayName: '电话', width: 100, enableFiltering: false },
                                        { name: 'email', displayName: '邮件', width: 100, enableFiltering: false },
                                        { name: 'dept.dept', displayName: '部门', width: 100, enableFiltering: false },
                                        { name: 'role[0].role', displayName: '角色', width: 100, enableFiltering: false }
                                    ];

                                    $scope.gridOptions.onRegisterApi = function(gridApi) {
                                        $scope.gridApi = gridApi;
                                        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
                                            var filtersData = $scope.memoryfilterData;
                                            filtersData.idx = newPage - 1;
                                            filtersData.sum = pageSize;
                                            $scope.loadData(filtersData);
                                            //console.log(pageSize);
                                            // $scope.loadData({"idx":newPage-1,"sum":pageSize});                                            
                                        });

                                        gridApi.selection.on.rowSelectionChanged($scope, function(data) {
                                            $scope.selected.item = data.entity;
                                            //console.log(data);
                                        });
                                        gridApi.core.on.filterChanged($scope, function() {
                                            var grid = this.grid;

                                            var filtersData = {
                                                idx: 0,
                                                sum: 10,
                                                "user": { "roledata": { "rolecode": "roleset" } }
                                            };
                                            angular.forEach(grid.columns, function(item) {
                                                if (item.enableFiltering) {
                                                    console.log("item.filters[0]=" + JSON.stringify(item.filters));
                                                    if (angular.isDefined(item.filters[0].term) && item.filters[0].term != '') {
                                                        if (angular.isUndefined(filtersData['user'])) {
                                                            filtersData['user'] = {};
                                                        }
                                                        filtersData['user'][item.field] = item.filters[0].term;
                                                    }
                                                }
                                            });
                                            $scope.memoryfilterData = filtersData;
                                            $scope.loadData(filtersData);
                                        });

                                    };
                                    $scope.memoryfilterData = {
                                        "idx": 0,
                                        "sum": 10,
                                        "user": { "roledata": { "rolecode": "roleset" } }
                                    }

                                    $scope.loadData = function(filterData) {
                                        console.log("filtersData=111" + JSON.stringify(filterData))
                                        items.fetchItems(filterData, APIService).then(function(data) {
                                            var myData = Restangular.stripRestangular(data);
                                            $scope.gridOptions.totalItems = myData.totalNum;
                                            $scope.myData = myData.list;
                                        });
                                    };
                                    $scope.title = title;

                                    $scope.loadData({
                                        idx: 0,
                                        sum: 10,
                                        "user": { "roledata": { "rolecode": "roleset" } }
                                    });

                                    $scope.selected = {
                                        item: {}
                                    };

                                    $scope.ok = function() {
                                        // if(onDataCallback&&angular.isFunction(onDataCallback)){
                                        //     onDataCallback($scope.selected.item, parentScope);
                                        // }
                                        $modalInstance.close($scope.selected.item);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return {
                                            fetchItems: function(filterData, APIService) {
                                                filterData = filterData || {};
                                                if (angular.isDefined(filterData.idx) && filterData.idx == null) {
                                                    filterData = {
                                                        idx: 0,
                                                        sum: 10,
                                                        "user": { "roledata": { "rolecode": "roleset" } }
                                                    };
                                                }
                                                return options.templateOptions.fetchItems(filterData, APIService);
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular: function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    onDataCallback: function() {
                                        return options.templateOptions.callback;
                                    },
                                    parentScope: function() {
                                        return options.templateOptions.that;
                                    }

                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                // console.log(selectedItem);
                                options.value(selectedItem);
                                if (options.templateOptions.callback && angular.isFunction(options.templateOptions.callback)) {
                                    options.templateOptions.callback(selectedItem, options.templateOptions.that);
                                }
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            },
            controller: ['$scope', function($scope) {
                $scope.options.templateOptions.that = $scope;
                if ($scope.options.templateOptions.translata && angular.isFunction($scope.options.templateOptions.translata)) {
                    $scope.model[$scope.options.key] = $scope.options.templateOptions.translata($scope.options, $scope.model);
                }
            }]
        });
        //用户多选控件
        formlyConfigProvider.setType({
            name: "ui-multiuserselect",
            templateUrl: 'assets/views/customform/tpl/ui-multiuserselect.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        openModal: function(size, options, modal, model) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                controller: function($scope, $modalInstance, i18nService, $timeout, items, title, Restangular, APIService, selectItems) {
                                    $scope.langs = i18nService.getAllLangs();
                                    $scope.lang = 'zh-cn';
                                    i18nService.setCurrentLang($scope.lang);
                                    $scope.gridOptions = {};
                                    $scope.gridOptions.data = 'myData';
                                    $scope.gridOptions.enableColumnResizing = true;
                                    $scope.gridOptions.enableFiltering = true;
                                    $scope.gridOptions.enableGridMenu = true;
                                    $scope.gridOptions.showGridFooter = true;
                                    $scope.gridOptions.showColumnFooter = true;
                                    $scope.gridOptions.fastWatch = true;
                                    $scope.gridOptions.useExternalFiltering = true;
                                    $scope.gridOptions.useExternalPagination = true;
                                    $scope.gridOptions.paginationPageSizes = [10];
                                    $scope.gridOptions.paginationPageSize = 10;
                                    $scope.gridOptions.multiSelect = true;

                                    $scope.gridOptions.rowIdentity = function(row) {
                                        return row.id;
                                    };
                                    $scope.gridOptions.getRowIdentity = function(row) {
                                        return row.id;
                                    };
                                    //{"id":1,"phone":"15071189091","name":"管理员","gender":"男","flag":1,"email":"asda@qq.com","account":"000001","group":[{"id":3,"groupName":"运行监控科"}]}
                                    $scope.gridOptions.columnDefs = [
                                        // { name:'id', width:80, enableFiltering:false},
                                        { name: 'account', displayName: '账号', width: 140 },
                                        { name: 'name', displayName: '名称', width: 100 },
                                        { name: 'gender', displayName: '性别', width: 140, enableFiltering: false },
                                        { name: 'phone', displayName: '电话', width: 100, enableFiltering: false },
                                        { name: 'email', displayName: '邮件', width: 100, enableFiltering: false },
                                        { name: 'dept.dept', displayName: '部门', width: 100, enableFiltering: false },
                                        { name: 'group[0].groupName', displayName: '职位', width: 100, enableFiltering: false }
                                    ];

                                    $scope.selected = {
                                        items: selectItems
                                    };
                                    $scope.gridOptions.onRegisterApi = function(gridApi) {
                                        $scope.gridApi = gridApi;
                                        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
                                            var filtersData = $scope.memoryfilterData;
                                            filtersData.idx = newPage - 1;
                                            filtersData.sum = pageSize;
                                            $scope.loadData(filtersData);
                                            // $scope.loadData({"idx":newPage-1,"sum":pageSize});                                            
                                        });
                                        gridApi.selection.on.rowSelectionChanged($scope, function(scope) {
                                            var j = 0;
                                            for (var i = 0; i <= scope.grid.appScope.selected.items.length; i++) {
                                                if (scope.grid.appScope.selected.items[i] == scope.entity) {
                                                    j++;
                                                    break;
                                                }
                                            }
                                            if (j == 1) {
                                                scope.grid.appScope.selected.items.splice(i, 1);
                                            } else {
                                                scope.grid.appScope.selected.items.push(scope.entity)
                                                for (var i = 0; i < scope.grid.appScope.selected.items.length; i++) {
                                                    for (var z = 0; z < scope.grid.appScope.selected.items.length; z++) {
                                                        // console.log("$scope.selected.items="+JSON.stringify($scope.selected.items));
                                                        // console.log("scope.grid.appScope.selected.items="+JSON.stringify(scope.grid.appScope.selected.items))
                                                        if (angular.isDefined(scope.grid.appScope.selected.items) && scope.grid.appScope.selected.items[i].id == scope.grid.appScope.selected.items[z].id && i != z) {
                                                            scope.grid.appScope.selected.items.splice(i, 1);
                                                        }
                                                    }
                                                }
                                            }
                                        });
                                        // gridApi.selection.on.rowSelectionChanged($scope, function($scope, rows){

                                        //     $scope.grid.appScope.selected.items.push($scope.entity);
                                        // });
                                        gridApi.core.on.filterChanged($scope, function() {
                                            var grid = this.grid;
                                            var filtersData = {
                                                idx: 0,
                                                sum: 10,
                                                "user": { "roledata": { "rolecode": "roleset" } }
                                            };
                                            angular.forEach(grid.columns, function(item) {
                                                if (item.enableFiltering) {
                                                    //console.log("filtersData="+JSON.stringify(filtersData))
                                                    if (angular.isDefined(item.filters[0].term) && item.filters[0].term != '') {
                                                        if (angular.isUndefined(filtersData['user'])) {
                                                            filtersData['user'] = {};
                                                        }
                                                        filtersData['user'][item.field] = item.filters[0].term;
                                                    }
                                                }
                                            });
                                            $scope.memoryfilterData = filtersData;
                                            $scope.loadData(filtersData);
                                        });

                                    };
                                    $scope.memoryfilterData = {
                                        "idx": 0,
                                        "sum": 10,
                                        "user": { "roledata": { "rolecode": "roleset" } }
                                    }
                                    $scope.loadData = function(filterData) {
                                        // console.log(" filtersData['user'][item.field]=111"+JSON.stringify(filterData));
                                        items.fetchItems(filterData, APIService).then(function(data) {
                                            var myData = Restangular.stripRestangular(data);
                                            $scope.gridOptions.totalItems = myData.totalNum;
                                            $scope.myData = myData.list;
                                            //console.log($scope.gridOptions.pagination.getTotalPages());
                                            // if($scope.selected.items){
                                            //     angular.forEach($scope.selected.items,function(selectItem){
                                            //         $scope.gridApi.selection.selectRow(selectItem);
                                            //     });
                                            // }
                                        });
                                    };
                                    $scope.title = title;

                                    $scope.loadData({
                                        idx: 0,
                                        sum: 10,
                                        "user": { "roledata": { "rolecode": "roleset" } }
                                    });



                                    // $timeout(function(){
                                    //     if($scope.selected.items){
                                    //         angular.forEach($scope.selected.items,function(selectItem){
                                    //             $scope.gridApi.selection.selectRow(selectItem);
                                    //         });
                                    //     }
                                    // },2000)



                                    $scope.ok = function() {
                                        // $scope.selected.items = $scope.gridApi.selection.getSelectedRows();
                                        $modalInstance.close($scope.selected.items);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return {
                                            fetchItems: function(filterData, APIService) {
                                                filterData = filterData || {};
                                                if (angular.isDefined(filterData.idx) && filterData.idx == null) {
                                                    filterData = {
                                                        idx: 0,
                                                        sum: 10,
                                                        "user": { "roledata": { "rolecode": "roleset" } }
                                                    };
                                                }
                                                return options.templateOptions.fetchItems(filterData, APIService);
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular: function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    selectItems: function() {
                                        return model || [];
                                    }
                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                options.value(selectedItem);
                                options.formControl.$validate();
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    },
                    validators: {
                        required: {
                            expression: function(viewValue, modelValue) {
                                var value = modelValue || viewValue;
                                return value.length >= 1;
                            }
                        }
                    }
                };
            },
            controller: ['$scope', function($scope) {
                $scope.model[$scope.options.key] = [];
                $scope.remove = function(itemId) {
                    angular.forEach($scope.model[$scope.options.key], function(entry, index) {
                        if (entry.id == itemId) {
                            $scope.model[$scope.options.key].splice(index, 1);
                            console.log($scope.options.formControl)
                            $scope.options.formControl.$validate();
                        } else {

                        }
                    });
                }
            }]
        });


        //选项选择控件
        formlyConfigProvider.setType({
            name: "ui-modelselect",
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-modelselect.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        openModal: function(size, options, modal) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/checktable-modal-content.html',
                                controller: function($scope, $modalInstance, items, title, Restangular, APIService, i18nService) {
                                    $scope.langs = i18nService.getAllLangs();
                                    $scope.lang = 'zh-cn';
                                    i18nService.setCurrentLang($scope.lang);
                                    $scope.gridOptions = {};
                                    $scope.gridOptions.data = 'myData';
                                    $scope.gridOptions.enableColumnResizing = true;
                                    $scope.gridOptions.enableFiltering = true;
                                    $scope.gridOptions.enableGridMenu = true;
                                    $scope.gridOptions.showGridFooter = true;
                                    $scope.gridOptions.showColumnFooter = true;
                                    $scope.gridOptions.fastWatch = true;
                                    $scope.gridOptions.useExternalPagination = true;
                                    $scope.gridOptions.useExternalFiltering = true;
                                    $scope.gridOptions.paginationPageSizes = [10];
                                    $scope.gridOptions.paginationPageSize = 10;
                                    $scope.gridOptions.multiSelect = false;

                                    $scope.gridOptions.rowIdentity = function(row) {
                                        return row.id;
                                    };
                                    $scope.gridOptions.getRowIdentity = function(row) {
                                        return row.id;
                                    };

                                    $scope.gridOptions.columnDefs = items.columnDefs();

                                    $scope.gridOptions.onRegisterApi = function(gridApi) {
                                        $scope.gridApi = gridApi;
                                        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
                                            // console.log(newPage);
                                            // console.log(pageSize);
                                            $scope.loadData({ "idx": newPage - 1, "sum": pageSize });
                                        });

                                        gridApi.core.on.filterChanged($scope, function() {
                                            var grid = this.grid;
                                            var filtersData = {
                                                idx: 0,
                                                sum: 10
                                            };
                                            angular.forEach(grid.columns, function(item) {
                                                if (item.enableFiltering) {
                                                    if (angular.isDefined(item.filters[0].term) && item.filters[0].term != '') {
                                                        // console.log("filtersData="+JSON.stringify(filtersData))
                                                        if (angular.isUndefined(filtersData['incident'])) {
                                                            filtersData['incident'] = {};
                                                        }
                                                        filtersData['incident'][item.field] = item.filters[0].term;
                                                        if (angular.isUndefined(filtersData['problem'])) {
                                                            filtersData['problem'] = {};
                                                        }
                                                        filtersData['problem'][item.field] = item.filters[0].term;
                                                        if (angular.isUndefined(filtersData['change'])) {
                                                            filtersData['change'] = {};
                                                        }
                                                        filtersData['change'][item.field] = item.filters[0].term;
                                                        if (angular.isUndefined(filtersData['release'])) {
                                                            filtersData['release'] = {};
                                                        }
                                                        filtersData['release'][item.field] = item.filters[0].term;
                                                    }
                                                }
                                            });
                                            $scope.loadData(filtersData);
                                        });


                                        gridApi.selection.on.rowSelectionChanged($scope, function(data) {
                                            $scope.selected.item = data.entity;
                                            //console.log(data);
                                        });
                                    };

                                    $scope.loadData = function(filterData) {
                                        items.fetchItems(filterData, APIService).then(function(data) {
                                            var myData = Restangular.stripRestangular(data);
                                            $scope.gridOptions.totalItems = myData.totalNum;
                                            $scope.myData = myData.list;
                                        });
                                    };

                                    $scope.title = title;

                                    $scope.loadData({
                                        idx: 0,
                                        sum: 10
                                    });

                                    $scope.selected = {
                                        item: {}
                                    };

                                    $scope.ok = function() {
                                        //console.log($scope.selected.item);
                                        $modalInstance.close($scope.selected.item);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    items: function() {
                                        return {
                                            fetchItems: function(filterData, APIService) {
                                                filterData = filterData || {};
                                                // if(!filterData.idx){
                                                if (angular.isDefined(filterData.idx) && filterData.idx == null) {
                                                    filterData = {
                                                        idx: 0,
                                                        sum: 10
                                                    };
                                                }
                                                return options.templateOptions.fetchItems(filterData, APIService, options);
                                            },
                                            columnDefs: function() {
                                                return options.templateOptions.columnDefs;
                                            }
                                        };
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular: function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    }
                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                options.value(selectedItem);
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                };
            }
        });
        //工单控件
        formlyConfigProvider.setType({
            name: 'ui-workernumber',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-workernumber.html',
            controller: ['$scope', function($scope) {
                setTimeout(function() {
                    $scope.options.templateOptions.getWorkernumber($scope.options.templateOptions.ApiService).then(function(result) {
                        var modelData = $scope.options.templateOptions.Restangular.stripRestangular(result);
                        if (modelData.status == 200) {
                            $scope.model[$scope.options.key] = modelData.data;
                            $scope.options.initialValue = $scope.model[$scope.options.key];
                        }
                    });
                }, 1000);
            }]
        });
        //无上传按钮附件上传组件
        formlyConfigProvider.setType({
            name: 'ui-dropfilenotup',
            templateUrl: 'assets/views/customform/tpl/ui-dropfilenotup.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            controller: ['$scope', function($scope) {
                if (angular.isUndefined($scope.form.dropState)) {
                    $scope.form.dropState = false;
                }
                //附件上传数据
                var uploader = $scope.uploader = $scope.options.templateOptions.fileUploader;
                //$scope.options.templateOptions.uploader();

                // FILTERS
                uploader.filters.push({
                    name: 'customFilter',
                    fn: function(item /*{File|FileLikeObject}*/ , options) {
                        return this.queue.length < 10;
                    }
                });


                $scope.dropfile = function(APIService, processInstanceId, taskId, userId) {
                    uploader.onBeforeUploadItem = function(item) {
                        item.url = APIService.saveAttachments(processInstanceId, taskId, userId).getRequestedUrl();
                        item.formData.push({ 'fileName': item.file.name });
                        console.info('onBeforeUploadItem', item);
                    };
                    uploader.uploadAll();
                }

                // CALLBACKS
                uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
                    console.info('onWhenAddingFileFailed', item, filter, options);
                };
                uploader.onAfterAddingFile = function(fileItem) {
                    console.info('onAfterAddingFile', fileItem);
                };
                uploader.onAfterAddingAll = function(addedFileItems) {
                    console.info('onAfterAddingAll', addedFileItems);
                };
                uploader.onBeforeUploadItem = function(item) {
                    // if($scope.uploader.getNotUploadedItems().length>0&&response.data.processInstanceId){
                    //     // $scope.uploader.options.url();
                    //     $scope.uploader.onBeforeUploadItem = function(item) {
                    //         item.url = api_bpm_domain.saveAttachments($stateParams.processInstanceId,$stateParams.taskId,$scope.user.id).getRequestedUrl();
                    //         console.info('onBeforeUploadItem', item);
                    //     };
                    //     $scope.uploader.uploadAll();
                    // }
                    console.info('onBeforeUploadItem', item);
                };
                uploader.onProgressItem = function(fileItem, progress) {
                    console.info('onProgressItem', fileItem, progress);
                };
                uploader.onProgressAll = function(progress) {
                    console.info('onProgressAll', progress);
                };
                uploader.onSuccessItem = function(fileItem, response, status, headers) {
                    console.info('onSuccessItem', fileItem, response, status, headers);
                };
                uploader.onErrorItem = function(fileItem, response, status, headers) {
                    console.info('onErrorItem', fileItem, response, status, headers);
                };
                uploader.onCancelItem = function(fileItem, response, status, headers) {
                    console.info('onCancelItem', fileItem, response, status, headers);
                };
                uploader.onCompleteItem = function(fileItem, response, status, headers) {
                    console.info('onCompleteItem', fileItem, response, status, headers);
                };
                uploader.onCompleteAll = function() {
                    console.info('onCompleteAll');
                };
            }]
        });
        //附件上传列表组件
        formlyConfigProvider.setType({
            name: 'ui-dropfile',
            templateUrl: 'assets/views/customform/tpl/ui-dropfile.html',
            wrapper: ['bootstrapLabel', 'bootstrapHasError'],
            controller: ['$scope', function($scope) {
                if (angular.isUndefined($scope.form.dropState)) {
                    $scope.form.dropState = false;
                }
                //附件上传数据
                var uploader = $scope.uploader = $scope.options.templateOptions.fileUploader;
                //$scope.options.templateOptions.uploader();

                // FILTERS
                uploader.filters.push({
                    name: 'customFilter',
                    fn: function(item /*{File|FileLikeObject}*/ , options) {
                        return this.queue.length < 10;
                    }
                });


                $scope.dropfile = function(APIService, processInstanceId, taskId, userId) {
                    uploader.onBeforeUploadItem = function(item) {
                        item.url = APIService.saveAttachments(processInstanceId, taskId, userId).getRequestedUrl();
                        item.formData.push({ 'fileName': item.file.name });
                        console.info('onBeforeUploadItem', item);
                    };
                    uploader.uploadAll();
                }

                // CALLBACKS
                uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
                    console.info('onWhenAddingFileFailed', item, filter, options);
                };
                uploader.onAfterAddingFile = function(fileItem) {
                    console.log($scope.uploader);
                    console.log(uploader)
                    console.info('onAfterAddingFile', fileItem);
                };
                uploader.onAfterAddingAll = function(addedFileItems) {
                    console.info('onAfterAddingAll', addedFileItems);
                };
                uploader.onBeforeUploadItem = function(item) {
                    // if($scope.uploader.getNotUploadedItems().length>0&&response.data.processInstanceId){
                    //     // $scope.uploader.options.url();
                    //     $scope.uploader.onBeforeUploadItem = function(item) {
                    //         item.url = api_bpm_domain.saveAttachments($stateParams.processInstanceId,$stateParams.taskId,$scope.user.id).getRequestedUrl();
                    //         console.info('onBeforeUploadItem', item);
                    //     };
                    //     $scope.uploader.uploadAll();
                    // }
                    console.info('onBeforeUploadItem', item);
                };
                uploader.onProgressItem = function(fileItem, progress) {
                    console.info('onProgressItem', fileItem, progress);
                };
                uploader.onProgressAll = function(progress) {
                    console.info('onProgressAll', progress);
                };
                uploader.onSuccessItem = function(fileItem, response, status, headers) {
                    console.info('onSuccessItem', fileItem, response, status, headers);
                };
                uploader.onErrorItem = function(fileItem, response, status, headers) {
                    console.info('onErrorItem', fileItem, response, status, headers);
                };
                uploader.onCancelItem = function(fileItem, response, status, headers) {
                    console.info('onCancelItem', fileItem, response, status, headers);
                };
                uploader.onCompleteItem = function(fileItem, response, status, headers) {
                    console.info('onCompleteItem', fileItem, response, status, headers);
                };
                uploader.onCompleteAll = function() {
                    console.info('onCompleteAll');
                };
            }]
        });

        //附件下载列表组件
        formlyConfigProvider.setType({
            name: 'ui-dropfiletable',
            templateUrl: 'assets/views/customform/tpl/ui-dropfiletable.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refresh: function(APIService, processInstanceId, data) {
                            return APIService.listAttachments(processInstanceId, data);
                        },
                        downloadUri: function(APIService, contentId) {
                            return APIService.downloadAttachment(contentId).getRequestedUrl();
                        },
                        refreshDelay: 0
                    }
                };
            },
            controller: ['$scope', '$timeout', function($scope, $timeout) {
                var _refreshDelayPromise;
                $scope.downloadUrl = function(contentId) {
                    return $scope.options.templateOptions.downloadUri($scope.options.templateOptions.ApiService, contentId) || '#';
                };

                /**
                 * refresh
                 */
                $scope._refresh = function(refreshAttr) {
                    if (refreshAttr !== undefined) {
                        if (_refreshDelayPromise) {
                            $timeout.cancel(_refreshDelayPromise);
                        }
                        _refreshDelayPromise = $timeout(function() {
                            $scope.options.templateOptions.refresh($scope.options.templateOptions.ApiService,
                                $scope.options.templateOptions.processInstanceId, { 'idx': 0, 'sum': 1000 }).then(function(response) {
                                var myData = $scope.options.templateOptions.Restangular.stripRestangular(response);
                                if (myData) {
                                    $scope.attachments = myData.data;
                                }
                            });
                        }, $scope.options.templateOptions.refreshDelay);
                    }
                }

                $scope._refresh({});
            }]
        });

        formlyConfigProvider.setType({
            name: 'ui-paralleltask',
            templateUrl: 'assets/views/customform/tpl/ui-paralleltask.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        refresh: function(APIService, processInstanceId, data) {
                            //return APIService.listAttachments(processInstanceId, data);
                        },
                        refreshDelay: 0
                    }
                };
            },
            controller: ['$scope', '$timeout', function($scope, $timeout) {}]
        });

        //repeatSection
        //
        formlyConfigProvider.setType({
            name: 'ui-repeatSection',
            templateUrl: 'assets/views/customform/tpl/ui-repeatSection.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        unique: 1,
                        initDisplay: false
                    }
                };
            },
            controller: function($scope) {
                //$scope.options.templateOptions.unique;
                $scope.formOptions = { formState: $scope.formState };
                $scope.addNew = addNew;

                $scope.copyFields = copyFields;

                function copyFields(fields) {
                    fields = angular.copy(fields);
                    addRandomIds(fields);
                    return fields;
                }

                function addNew() {
                    $scope.model[$scope.options.key] = $scope.model[$scope.options.key] || [];
                    var repeatsection = $scope.model[$scope.options.key];
                    var lastSection = repeatsection[repeatsection.length - 1];
                    var newsection = {};
                    // if (lastSection) {
                    //   newsection = angular.copy(lastSection);
                    // }
                    repeatsection.push(newsection);
                }

                function addRandomIds(fields) {
                    $scope.options.templateOptions.unique++;
                    angular.forEach(fields, function(field, index) {
                        if (field.fieldGroup) {
                            addRandomIds(field.fieldGroup);
                            return; // fieldGroups don't need an ID
                        }

                        if (field.templateOptions && field.templateOptions.fields) {
                            addRandomIds(field.templateOptions.fields);
                        }

                        field.id = field.id || (field.key + '_' + index + '_' + $scope.options.templateOptions.unique + getRandomInt(0, 9999));
                    });
                }

                function getRandomInt(min, max) {
                    return Math.floor(Math.random() * (max - min)) + min;
                }

                if ($scope.options.templateOptions.initDisplay) {
                    addNew();
                }
            }
        });
        //时间轴任务列表组件

        //列表组件
        //状态追踪
        formlyConfigProvider.setType({
            name: 'ui-followStatus',
            templateUrl: 'assets/views/customform/tpl/ui-followStatus.html',
            controller: ['$scope', 'api_bpm_data', 'Restangular', function($scope, api_bpm_data, Restangular) {
                setTimeout(function() {
                    var pkey = $scope.options.templateOptions.pkey;
                    var dataId = $scope.model.id;
                    api_bpm_data.fetchData(pkey, dataId).then(function(response) {
                        if (response) {
                            var myData = Restangular.stripRestangular(response);
                            var processInstanceId = myData.data.processInstanceId;

                            $scope.options.templateOptions.getData($scope.model, $scope.options.templateOptions.ApiService, processInstanceId).then(function(result) {
                                if (result.status == 200) {
                                    var newData = Restangular.stripRestangular(result);
                                    $scope.followData = newData.data;
                                }
                            });

                        }
                    })
                }, 10);
            }]
        });
        //历史记录
        // formlyConfigProvider.setType({
        //     name: 'ui-history',
        //     templateUrl: 'assets/views/customform/tpl/ui-history.html',
        //     controller: ['$scope', 'api_bpm_data', 'Restangular', function($scope, api_bpm_data, Restangular) {
        //         setTimeout(function() {
        //             var pkey = $scope.options.templateOptions.pkey;
        //             var dataId = $scope.model.id;
        //             api_bpm_data.fetchData(pkey, dataId).then(function(response) {
        //                 if (response) {
        //                     var myData = Restangular.stripRestangular(response);
        //                     var processInstanceId = myData.data.processInstanceId;

        //                     $scope.options.templateOptions.getData($scope.model, $scope.options.templateOptions.ApiService, processInstanceId).then(function(result) {
        //                         if (result.status == 200) {
        //                             var newData = Restangular.stripRestangular(result);
        //                             var long = newData.data.length - 1;
        //                             $scope.followData = newData.data[long];
        //                         }
        //                     });

        //                 }
        //             })
        //         }, 10);
        //     }]
        // });
        //知识库按钮组件
        formlyConfigProvider.setType({
            name: 'ui-search',
            templateUrl: 'assets/views/customform/tpl/ui-knowledge.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        search: function(size, options, modal, keys, fields, el) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/search-knowledge.html',
                                controller: function($scope, i18nService, $modalInstance, searchKey, title, Restangular, APIService, modelscope, relatedAction) {
                                    $scope.langs = i18nService.getAllLangs();
                                    $scope.lang = 'zh-cn';
                                    i18nService.setCurrentLang($scope.lang);

                                    $scope.options = {
                                        language: 'zh-cn',
                                        allowedContent: true,
                                        entities: false
                                    };

                                    $scope.onReady = function() {
                                        // ...
                                    };

                                    $scope.searchKey = searchKey;
                                    $scope.search = function(key) {
                                        APIService.searchSolutionByKey(key).then(function(response) {
                                            var myData = Restangular.stripRestangular(response);
                                            var status = myData.status;
                                            if (status == "500") {
                                                //toaster.pop('warning', '没有数据', '查询'+keys+'没有数据');
                                            } else if (status == "200") {
                                                var data = myData.data;
                                                if (data.length > 0) {
                                                    $scope.searchData = data;
                                                }
                                            }
                                        });
                                    };

                                    $scope.related = function(entity) {
                                        // angular.forEach(fields, function(field){
                                        //     if(field.key == 'directClose'){
                                        //         field.value(true);
                                        //         modelscope.$parent.$parent.$parent.model['start_code']='close';

                                        //     }
                                        //     if(field.key == 'handleDescription'){

                                        //         field.model['handleDescription']=tentity.content;
                                        //     }
                                        // });

                                        if (relatedAction && angular.isFunction(relatedAction)) {
                                            relatedAction(fields, modelscope, entity);
                                        }
                                        $scope.cancel();
                                        // angular.forEach(fields,function(field){

                                        // });                                            

                                    }

                                    $scope.title = title;

                                    $scope.search(searchKey);

                                    $scope.selected = {
                                        item: {}
                                    };

                                    $scope.ok = function() {
                                        //console.log($scope.selected.item);
                                        $modalInstance.close($scope.selected.item);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    searchKey: function() {
                                        return keys;
                                    },
                                    title: function() {
                                        return options.templateOptions.modalTitle;
                                    },
                                    Restangular: function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    modelscope: function() {
                                        return el.$parent;
                                    },
                                    relatedAction: function() {
                                        return options.templateOptions.relationAction;
                                    }
                                }
                            });
                            // modalInstance.result.then(function(selectedItem) {
                            //     options.value(selectedItem);
                            // }, function() {
                            //     //console.log('Modal dismissed at: ' + new Date());
                            // });
                        }
                    }
                };
            },
            controller: ['$scope', function($scope) {
                // $scope.searchModal = $scope.model[$scope.options.key];
                // $scope.$watch('searchModal',function(newValue, oldValue){
                //     if (newValue === oldValue) { return; }
                //     if (newValue.flag == oldValue.flag) { return; }
                //     if (angular.isDefined(newValue.flag)&&(newValue.flag==true)){
                //         if (newValue.searchKey!=''&&angular.isDefined(newValue.searchKey)){
                //             $scope.options.templateOptions.search('lg',$scope.options,newValue.searchKey);
                //         }
                //     }
                // })
                //
            }]
        });


        //cmdb控件
        formlyConfigProvider.setType({
            name: 'ui-cmdb',
            extends: 'input',
            templateUrl: 'assets/views/customform/tpl/ui-cmdb.html',
            defaultOptions: function(options) {
                return {
                    templateOptions: {
                        onClick: function(size, options, modal, event, model) {
                            var modalInstance = modal.open({
                                templateUrl: 'assets/views/customform/tpl/cmdb-modal-content.html',
                                controller: function($scope, $modalInstance, title, Restangular, APIService, ConfigDataService, ConfigFormService, SweetAlert, Toaster) {

                                    var width = $scope.width = 600;
                                    var height = $scope.height = 400;
                                    var tree;
                                    var d3 = window.d3;
                                    $scope.my_tree_handler = function(branch) {
                                        //var _ref;
                                        var classify = $scope.classify = branch.prefix.toLowerCase() + branch.sign;
                                        APIService.query({ 'sign': classify }).then(function(data) {
                                            var myData = Restangular.stripRestangular(data);
                                            console.log(myData.data.node);
                                            if (myData.data && myData.status == 200) {
                                                var ret = myData.data;
                                                redrawSvg(myData);
                                            }
                                        });
                                    };
                                    $scope.my_data = [];

                                    function convertListToTree(data, treeMap) {
                                        var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
                                        var root = null; //Initially set our loop to null
                                        var parentNode = null;
                                        //loop over data
                                        for (var i = 0; i < data.length; i++) {
                                            var datum = data[i];
                                            //each node will have children, so let's give it a "children" poperty
                                            datum.children = [];

                                            //add an entry for this node to the map so that any future children can
                                            //lookup the parent
                                            idToNodeMap[datum.id] = datum;

                                            //Does this node have a parent?
                                            if (typeof datum.parent === "undefined" || datum.parent == null) {
                                                //Doesn't look like it, so this node is the root of the tree
                                                root = datum;
                                                treeMap[datum.id] = root;
                                            } else {
                                                //This node has a parent, so let's look it up using the id
                                                parentNode = idToNodeMap[datum.parent.id];

                                                //We don't need this property, so let's delete it.
                                                delete datum.parent;

                                                //Let's add the current node as a child of the parent node.
                                                parentNode.children.push(datum);
                                            }
                                        }
                                        return root;
                                    }

                                    function convertParentToChildList(data) {
                                        var treeMap = {};
                                        var list = [];
                                        convertListToTree(data, treeMap);
                                        angular.forEach(treeMap, function(item) {
                                            list.push(item);
                                        });
                                        return list;
                                    }

                                    $scope.my_tree = tree = {};
                                    $scope.try_async_load = function() {
                                        $scope.my_data = [];
                                        $scope.select_treedata = [];
                                        $scope.doing_async = true;
                                        ConfigDataService.fetchDataList('ciclassify', { 'idx': 0, 'sum': 100 }).then(function(result) {
                                            $scope.select_treedata = $scope.my_data = convertParentToChildList(result['list']);
                                            $scope.doing_async = false;
                                        });
                                    };

                                    $scope.select_treedata = [];
                                    $scope.propTypeOptions = [];
                                    $scope.try_async_load();

                                    $scope.onFilterCallback = function(item) {
                                        //console.log(item);
                                        if (angular.isDefined(item.children) && item.children.length >= 1) {
                                            //not valid
                                        } else {
                                            var tempclassify = item.prefix.toLowerCase() + item.sign;
                                            $scope.cifilter_classic = tempclassify;
                                            ConfigFormService.renderTabForm(tempclassify).then(function(data) {
                                                var myData = Restangular.stripRestangular(data);
                                                $scope.propTypeOptions = myData;
                                            });
                                        }
                                    }

                                    $scope.onPropTypeChange = function(form) {
                                        $scope.propOptions = form.fields;
                                    }

                                    $scope.onPropChange = function(prop) {
                                        $scope.cifilter_prop = prop;
                                    }

                                    $scope.searchCI = function(searchKey, propObj, ciclassify) {
                                        //if(searchKey!=null&&searchKey.length>1){
                                        var searchData = {};
                                        if (angular.isUndefined(propObj)) {
                                            propObj = $scope.cifilter_prop;
                                        }
                                        if (angular.isUndefined(ciclassify)) {
                                            ciclassify = $scope.cifilter_classic;
                                        }
                                        searchData['sign'] = ciclassify;
                                        if (angular.isDefined(propObj)) {
                                            searchData[propObj.key] = searchKey;
                                        }
                                        APIService.query(searchData).then(function(response) {
                                            var data = Restangular.stripRestangular(response);
                                            //此处不清空nodes
                                            var node = data.data.node;
                                            var tempNode = [];
                                            //nodes 或者links 要去重
                                            for (var i = 0; i < node.length; i++) {
                                                var tmp = 0;
                                                for (var j = 0; j < nodes.length; j++) {
                                                    if (node[i].uuid == nodes[j].uuid) {
                                                        tmp++;
                                                        break;
                                                    }
                                                }
                                                if (tmp == 0) {
                                                    tempNode.push(node[i]);
                                                }
                                            }
                                            for (var i = 0; i < tempNode.length; i++) { //nodes  不清空
                                                nodes.push(tempNode[i]);
                                            }

                                            restart();
                                        })
                                    }

                                    $scope.refresh = function() {
                                        nodes.length = 0;
                                        links.length = 0;

                                        restart();
                                    }

                                    $scope.traversal = function() {
                                        if ($scope.selected_node == null) {
                                            SweetAlert.swal({
                                                title: "错误的操作!",
                                                text: "没有配置项被选中!",
                                                type: "error"
                                            });
                                        } else {
                                            var uuid = $scope.selected_node.uuid;
                                            APIService.traversal(uuid).then(function(response) {
                                                var d = response.data;
                                                var node = d.node;
                                                var link = d.edge;
                                                var tempNode = [];
                                                var tempLink = [];
                                                //nodes 或者links 要去重
                                                for (var i = 0; i < node.length; i++) {
                                                    var tmp = 0;
                                                    for (var j = 0; j < nodes.length; j++) {
                                                        if (node[i].id == nodes[j].id) {
                                                            tmp++;
                                                            break;
                                                        }
                                                    }
                                                    if (tmp == 0) {
                                                        tempNode.push(node[i]);
                                                    }
                                                }

                                                for (var i = 0; i < link.length; i++) {
                                                    var tmp = 0;
                                                    for (var j = 0; j < links.length; j++) {
                                                        if (link[i].id == links[j].id) {
                                                            tmp++;
                                                            break;
                                                        }
                                                    }
                                                    if (tmp == 0) {
                                                        tempLink.push(link[i]);
                                                    }
                                                }
                                                //数据写入页面
                                                for (var i = 0; i < tempNode.length; i++) { //nodes  不清空
                                                    nodes.push(tempNode[i]);
                                                }
                                                for (var i = 0; i < tempLink.length; i++) { //link  不清空
                                                    links.push(tempLink[i]);
                                                }
                                                //links转换
                                                for (var i = 0; i < links.length; i++) {
                                                    for (var j = 0; j < nodes.length; j++) {
                                                        if (links[i].source == nodes[j].id) {
                                                            links[i].source = nodes[j];
                                                        }
                                                        if (links[i].target == nodes[j].id) {
                                                            links[i].target = nodes[j];
                                                        }
                                                    }
                                                }

                                                restart();
                                            })
                                        }
                                    }

                                    var svg;
                                    var force;
                                    var drag_line, path, circle;
                                    //var svg = d3.select(angular.element('div#cmdbSVG')).append('svg').attr('width', width).attr('height', height);
                                    //var svg = angular.element('div#cmdbSVG').append('svg').attr('width', width).attr('height', height);
                                    //var svg = d3.select('#cmdbSVG').append('svg').attr('width', width).attr('height', height);
                                    var nodes = [],
                                        links = [];
                                    var treeNodes = [];
                                    //读取labels (node)
                                    var labels = [];

                                    function redrawSvg(json) {
                                        nodes.length = 0; //先清空
                                        links.length = 0;
                                        var data = json.data;
                                        for (var i = 0; i < data.node.length; i++) {
                                            nodes.push(data.node[i]);
                                        }

                                        restart();
                                    }

                                    //读取status (节点  连线)
                                    var statuses = [];
                                    ConfigDataService.fetchDataList('cistatus', { 'idx': 0, 'sum': 100 }).then(function(result) {
                                        if (result && result.status == 200) {
                                            d3.select('#nodeStatus').selectAll('option')
                                                .data(statuses).enter()
                                                .append('option')
                                                .attr('value', function(d) { return d.code; })
                                                .html(function(d) { return d.desc; });
                                        } else {
                                            SweetAlert.swal({
                                                title: "提示!",
                                                text: "服务器请求异常!",
                                                type: "error"
                                            });
                                        }
                                    });

                                    //查询relationship_type表 name 为表里的type,label为显示值
                                    var linkType = [];

                                    function fetchEdgeTypes() {
                                        ConfigDataService.fetchDataList('ciedgetype', { 'idx': 0, 'sum': 100 }).then(function(response) {
                                            if (response) {
                                                if (response['list']) {
                                                    linkType = response['list'];
                                                    // d3.select('#linkName').selectAll('option')
                                                    //     .data(linkType).enter()
                                                    //     .append('option')
                                                    //     .attr('value',function(d){return d.type;})
                                                    //     .html(function(d){ return d.label;});
                                                } else {
                                                    SweetAlert.swal({
                                                        title: "提示!",
                                                        text: "服务器请求异常!",
                                                        type: "error"
                                                    });
                                                }
                                            } else {
                                                SweetAlert.swal({
                                                    title: "提示!",
                                                    text: "服务器请求异常!",
                                                    type: "error"
                                                });
                                            }
                                        })
                                    }
                                    fetchEdgeTypes();
                                    /*
                                    // init D3 force layout
                                    var force = d3.layout.force()
                                        .nodes(nodes)
                                        .links(links)
                                        .size([width, height])
                                        .gravity(.05)
                                        .linkDistance(150)
                                        .linkStrength(2)
                                        .charge(-500)
                                        .on('tick', tick);

                                    // define arrow markers for graph links
                                    svg.append('svg:defs').append('svg:marker')
                                        .attr('id', 'end-arrow')
                                        .attr('viewBox', '0 -5 10 10')
                                        .attr('refX', 6)
                                        .attr('markerWidth', 3)
                                        .attr('markerHeight', 3)
                                        .attr('orient', 'auto')
                                      .append('svg:path')
                                        .attr('d', 'M0,-5L10,0L0,5')
                                        .attr('fill', '#000');

                                    svg.append('svg:defs').append('svg:marker')
                                        .attr('id', 'start-arrow')
                                        .attr('viewBox', '0 -5 10 10')
                                        .attr('refX', 4)
                                        .attr('markerWidth', 3)
                                        .attr('markerHeight', 3)
                                        .attr('orient', 'auto')
                                      .append('svg:path')
                                        .attr('d', 'M10,-5L0,0L10,5')
                                        .attr('fill', '#000');

                                    // line displayed when dragging new nodes
                                    var drag_line = svg.append('svg:path')
                                      .attr('class', 'link dragline hidden')
                                      .attr('d', 'M0,0L0,0');

                                    // handles to link and node element groups
                                    //(1)var path = svg.append('svg:g').selectAll('g')
                                    var path = svg.append('svg:g').selectAll('g'),
                                        circle = svg.append('svg:g').selectAll('g');
                                    */
                                    // mouse event vars
                                    var selected_node = null,
                                        selected_link = null,
                                        mousedown_link = null,
                                        mousedown_node = null,
                                        mouseup_node = null;

                                    function resetMouseVars() {
                                        mousedown_node = null;
                                        mouseup_node = null;
                                        mousedown_link = null;
                                    }

                                    // update force layout (called automatically each iteration)
                                    function tick() {
                                        // draw directed edges with proper padding from node centers
                                        path.selectAll('path').attr('d', function(d) {
                                            var deltaX = d.target.x - d.source.x,
                                                deltaY = d.target.y - d.source.y,
                                                dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
                                                normX = deltaX / dist,
                                                normY = deltaY / dist,
                                                sourcePadding = d.left ? 27 : 22,
                                                targetPadding = d.right ? 27 : 22,
                                                sourceX = d.source.x + (sourcePadding * normX),
                                                sourceY = d.source.y + (sourcePadding * normY),
                                                targetX = d.target.x - (targetPadding * normX),
                                                targetY = d.target.y - (targetPadding * normY);


                                            return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
                                        });



                                        circle.attr('transform', function(d) {
                                            return 'translate(' + d.x + ',' + d.y + ')';
                                        });
                                    }

                                    // update graph (called when needed)
                                    function restart() {
                                        //绑定link 数据
                                        path.datum(links);
                                        // path (link) group
                                        path = path.data(links, function(d) { return d.id; });

                                        var p = path.enter().append('svg:g');

                                        //update existing links
                                        path.selectAll('path').classed('selected', function(d) { return d === selected_link; })
                                            .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
                                            .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });

                                        // add new links
                                        p.append('svg:path')
                                            .attr('class', 'link')
                                            .attr('id', function(d) { return "path_" + d.id; })
                                            // .attr('startOffset', '0%')
                                            .classed('selected', function(d) { return d === selected_link; })
                                            .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
                                            .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
                                            .on('mousedown', function(d) {
                                                if (d3.event.ctrlKey) return;

                                                //去除没有提交的连线
                                                for (var i = 0; i < links.length; i++) {
                                                    if (links[i].id == -1 && d.id != -1) {
                                                        links.splice(i, 1);
                                                    }
                                                }

                                                // select link
                                                mousedown_link = d;
                                                if (mousedown_link === selected_link) {
                                                    selected_link = $scope.selected_link = null;
                                                    selected_node = $scope.selected_node = null;
                                                    //    d3.select("#linkDetail").attr('style','display:none');
                                                    //hideLinkForm(true);//return ;
                                                } else {
                                                    selected_link = $scope.selected_link = mousedown_link;
                                                    selected_node = $scope.selected_node = null;
                                                }
                                                selected_node = $scope.selected_node = null;

                                                restart();
                                            });


                                        p.append('svg:text')
                                            .attr('x', 30)
                                            .attr('y', 20)
                                            .attr('class', 'fontM')
                                            .append('textPath')
                                            .attr('xlink:xlink:href', function(d, i) { return "#path_" + d.id; })
                                            .html(function(d) {
                                                for (var i = 0; i < linkType.length; i++) {
                                                    if (linkType[i].type == d.name) {
                                                        return linkType[i].label;
                                                    }
                                                }
                                            });

                                        // remove old links
                                        path.exit().remove();


                                        // circle (node) group
                                        // NB: the function arg is crucial here! nodes are known by id, not by index!
                                        circle.datum(nodes);
                                        circle = circle.data(nodes, function(d) { return d.id; });

                                        // update existing nodes (reflexive & selected visual states)
                                        circle.selectAll('circle')
                                            .style('fill', function(d) { return (d === selected_node) ? d3.rgb(colors(d.label)).brighter().toString() : colors(d.label); })
                                            .style('fill-opacity', 0.75) // add by xi
                                            .classed('reflexive', function(d) { return d.reflexive; });


                                        // add new nodes
                                        var g = circle.enter().append('svg:g');
                                        //g.append('svg:circle').attr('r',22).style('fill','rgb(255,255,255)').style('stroke','rgb(255,255,255)').style('stroke-width','2');
                                        //g.append('svg:circle').attr('r',24).style('fill','rgb(255,255,255)').style('stroke', function(d) { return d3.rgb(colors(d.label)).darker().toString(); }).style('stroke-width','2');
                                        g.append('svg:circle').attr('r', 24).style('fill', function(d) { return (d === selected_node) ? 'rgb(153,153,153)' : 'rgb(255,255,255)'; }).style('stroke', function(d) { return d3.rgb(colors(d.label)).darker().toString(); }).style('stroke-width', '2');

                                        g.append('svg:circle')
                                            .attr('class', 'node')
                                            .attr('r', 18)
                                            .style('fill', function(d) { return (d === selected_node) ? d3.rgb(colors(d.label)).brighter().toString() : colors(d.label); })
                                            .style('stroke', function(d) { return d3.rgb(colors(d.label)).darker().toString(); })
                                            .style('fill-opacity', 0.25) //add by xj
                                            .style('stroke-opacity', 0.5) //add by xj
                                            .classed('reflexive', function(d) { return d.reflexive; });
                                        g.on('mouseover', function(d) {
                                                //if(!mousedown_node || d === mousedown_node) return;
                                                // enlarge target node
                                                //d3.select(this).attr('transform', 'scale(1.1)');
                                            })
                                            .on('mouseout', function(d) {
                                                //if(!mousedown_node || d === mousedown_node) return;
                                                // unenlarge target node
                                                //d3.select(this).attr('transform', '');
                                            })
                                            .on('mousedown', function(d) {
                                                if (d3.event.ctrlKey) return;
                                                //hideLinkForm(true);      
                                                //去除没有提交的连线
                                                for (var i = 0; i < links.length; i++) {
                                                    if (links[i].id == -1) {
                                                        links.splice(i, 1);
                                                    }
                                                }
                                                // select node
                                                mousedown_node = d;
                                                if (mousedown_node === selected_node) {
                                                    selected_node = $scope.selected_node = null;
                                                } else {
                                                    selected_node = $scope.selected_node = mousedown_node;
                                                    selected_link = $scope.selected_link = null;
                                                    // 点击节点  查询关系及节点 /traversal/{id}/{relation}
                                                    APIService.findRefById(selected_node.id).then(function(result) {
                                                        var d = result.data;
                                                        var node = d.node;
                                                        var link = d.edge;
                                                        var tempNode = [];
                                                        var tempLink = [];
                                                        //nodes 或者links 要去重
                                                        for (var i = 0; i < node.length; i++) {
                                                            var tmp = 0;
                                                            for (var j = 0; j < nodes.length; j++) {
                                                                if (node[i].id == nodes[j].id) {
                                                                    tmp++;
                                                                    break;
                                                                }
                                                            }
                                                            if (tmp == 0) {
                                                                tempNode.push(node[i]);
                                                            }
                                                        }

                                                        for (var i = 0; i < link.length; i++) {
                                                            var tmp = 0;
                                                            for (var j = 0; j < links.length; j++) {
                                                                if (link[i].id == links[j].id) {
                                                                    tmp++;
                                                                    break;
                                                                }
                                                            }
                                                            if (tmp == 0) {
                                                                tempLink.push(link[i]);
                                                            }
                                                        }
                                                        //数据写入页面
                                                        for (var i = 0; i < tempNode.length; i++) { //nodes  不清空
                                                            nodes.push(tempNode[i]);
                                                        }
                                                        for (var i = 0; i < tempLink.length; i++) { //link  不清空
                                                            links.push(tempLink[i]);
                                                        }
                                                        //links转换
                                                        for (var i = 0; i < links.length; i++) {
                                                            for (var j = 0; j < nodes.length; j++) {
                                                                if (links[i].source == nodes[j].id) {
                                                                    links[i].source = nodes[j];
                                                                }
                                                                if (links[i].target == nodes[j].id) {
                                                                    links[i].target = nodes[j];
                                                                }
                                                            }
                                                        }
                                                        restart();
                                                    });
                                                }


                                                // reposition drag line
                                                drag_line
                                                    .style('marker-end', 'url(#end-arrow)')
                                                    .classed('hidden', false)
                                                    .attr('d', 'M' + mousedown_node.x + ',' + mousedown_node.y + 'L' + mousedown_node.x + ',' + mousedown_node.y);

                                                restart();
                                            })
                                            .on('mouseup', function(d) {
                                                if (!mousedown_node) return;
                                            });

                                        // show node name
                                        g.append('svg:text')
                                            .attr('x', 0)
                                            .attr('y', 34)
                                            .attr('class', 'id')
                                            .text(function(d) { return d.name; }); //TODO 改为  d.name

                                        //设置图片    
                                        g.append('svg:foreignObject')
                                            .attr("width", 32)
                                            .attr("height", 32)
                                            .attr('x', "-16px")
                                            .attr('y', "-11px")
                                            .html(function(d) {
                                                for (var i = 0; i < labels.length; i++) {
                                                    if (d.label == labels[i].sign) {
                                                        return '<i class="icon iconfont">' + labels[i].iconname + '</i>';
                                                    }

                                                }
                                            });

                                        // remove old nodes
                                        circle.exit().remove();

                                        // set the graph in motion
                                        force.start();
                                    }

                                    function mousedown() {
                                        // prevent I-bar on drag
                                        //d3.event.preventDefault();

                                        // because :active only works in WebKit?
                                        svg.classed('active', true);

                                        if (mousedown_node) {
                                            viewNode(mousedown_node);
                                        }
                                        if (d3.event.ctrlKey || mousedown_node || mousedown_link) return;
                                        restart();
                                    }

                                    function mousemove() {
                                        if (!mousedown_node) return;

                                        // update drag line
                                        //drag_line.attr('d', 'M' + mousedown_node.x + ',' + mousedown_node.y + 'L' + d3.mouse(this)[0] + ',' + d3.mouse(this)[1]);

                                        //restart();
                                    }

                                    function mouseup() {
                                        if (mousedown_node) {
                                            // hide drag line
                                            drag_line
                                                .classed('hidden', true)
                                                .style('marker-end', '');
                                        }

                                        // because :active only works in WebKit?
                                        svg.classed('active', false);

                                        // clear mouse event vars
                                        resetMouseVars();
                                    }

                                    function spliceLinksForNode(node) {
                                        var toSplice = links.filter(function(l) {
                                            return (l.source === node || l.target === node);
                                        });
                                        toSplice.map(function(l) {
                                            links.splice(links.indexOf(l), 1);
                                        });
                                    }

                                    // only respond once per keydown
                                    var lastKeyDown = -1;

                                    function keydown() {
                                        //d3.event.preventDefault();

                                        if (lastKeyDown !== -1) return;
                                        lastKeyDown = d3.event.keyCode;

                                        // ctrl
                                        if (d3.event.keyCode === 17) {
                                            circle.call(force.drag);
                                            svg.classed('ctrl', true);
                                        }

                                        if (!selected_node && !selected_link) return;
                                        switch (d3.event.keyCode) {
                                            case 8: // backspace
                                            case 66: // B
                                                if (selected_link) {
                                                    // set link direction to both left and right
                                                    selected_link.left = true;
                                                    selected_link.right = true;
                                                }
                                                restart();
                                                break;
                                            case 76: // L
                                                if (selected_link) {
                                                    // set link direction to left only
                                                    selected_link.left = true;
                                                    selected_link.right = false;
                                                }
                                                restart();
                                                break;
                                            case 82: // R
                                                if (selected_node) {
                                                    // toggle node reflexivity
                                                    selected_node.reflexive = !selected_node.reflexive;
                                                } else if (selected_link) {
                                                    // set link direction to right only
                                                    selected_link.left = false;
                                                    selected_link.right = true;
                                                }
                                                restart();
                                                break;
                                        }
                                    }

                                    function keyup() {
                                        lastKeyDown = -1;

                                        // ctrl
                                        if (d3.event.keyCode === 17) {
                                            circle
                                                .on('mousedown.drag', null)
                                                .on('touchstart.drag', null);
                                            svg.classed('ctrl', false);
                                        }
                                    }

                                    function viewNode(node) {
                                        console.log(svg.attr('left'));
                                        //var el = angular.element('div.modal-dialog')[0];
                                        var title = $scope.selected_node.name + "-[" + $scope.selected_node.uuid + "]";
                                        if (!$scope.selected_node.props.state) { $scope.selected_node.props.state = "空" } else if ($scope.selected_node.props.state) {
                                            if ($scope.selected_node.props.state == "1") { $scope.selected_node.props.state = "未审核" } else if ($scope.selected_node.props.state == "2") { $scope.selected_node.props.state = "已审核" } else if ($scope.selected_node.props.state == "3") { $scope.selected_node.props.state = "不匹配" } else if ($scope.selected_node.props.state == "4") { $scope.selected_node.props.state = "丢失" }
                                        };
                                        if (!$scope.selected_node.name) { $scope.selected_node.name = "空" }
                                        if (!$scope.selected_node.status) { $scope.selected_node.statu = "空" }
                                        if (!$scope.selected_node.props.useradmin) { $scope.selected_node.props.useradmin = "空" }
                                        Toaster.pop({
                                            // type: 'info',
                                            // title: title,
                                            body: '<br/><p>搜索代码:' + $scope.selected_node.uuid + '</p>' +
                                                '<p>配置标题:' + $scope.selected_node.name + '</p>' +
                                                '<p>状态:' + $scope.selected_node.status + '</p>' +
                                                '<p>审核状态:' + $scope.selected_node.props.state + '</p>' +
                                                '<p>维护人员:' + $scope.selected_node.props.useradmin + '</p>',
                                            bodyOutputType: 'trustedHtml',
                                            timeout: 3000
                                        })
                                    }

                                    //GT 颜色与数值对照表
                                    function colors(sign) {
                                        //num=num>20?num%20:parseInt(num);
                                        for (var i = 0; i < labels.length; i++) {
                                            var entity = labels[i];
                                            if (sign == entity.sign) {
                                                return entity.color;
                                            }
                                            if (i == labels.length - 1 && sign != entity.sign) {
                                                return '#ffeeee';
                                            }
                                        }
                                    }
                                    $scope.init = function() {
                                        svg = d3.select('#cmdbSVG').append('svg').attr('width', width).attr('height', height);

                                        // init D3 force layout
                                        force = d3.layout.force()
                                            .nodes(nodes)
                                            .links(links)
                                            .size([width, height])
                                            .gravity(.05)
                                            .linkDistance(150)
                                            .linkStrength(2)
                                            .charge(-500)
                                            .on('tick', tick);

                                        // define arrow markers for graph links
                                        svg.append('svg:defs').append('svg:marker')
                                            .attr('id', 'end-arrow')
                                            .attr('viewBox', '0 -5 10 10')
                                            .attr('refX', 6)
                                            .attr('markerWidth', 3)
                                            .attr('markerHeight', 3)
                                            .attr('orient', 'auto')
                                            .append('svg:path')
                                            .attr('d', 'M0,-5L10,0L0,5')
                                            .attr('fill', '#000');

                                        svg.append('svg:defs').append('svg:marker')
                                            .attr('id', 'start-arrow')
                                            .attr('viewBox', '0 -5 10 10')
                                            .attr('refX', 4)
                                            .attr('markerWidth', 3)
                                            .attr('markerHeight', 3)
                                            .attr('orient', 'auto')
                                            .append('svg:path')
                                            .attr('d', 'M10,-5L0,0L10,5')
                                            .attr('fill', '#000');

                                        // line displayed when dragging new nodes
                                        drag_line = svg.append('svg:path')
                                            .attr('class', 'link dragline hidden')
                                            .attr('d', 'M0,0L0,0');

                                        // handles to link and node element groups
                                        //(1)var path = svg.append('svg:g').selectAll('g')
                                        path = svg.append('svg:g').selectAll('g');
                                        circle = svg.append('svg:g').selectAll('g');

                                        svg.on('mousedown', mousedown)
                                            .on('mousemove', mousemove)
                                            .on('mouseup', mouseup);
                                        d3.select(window)
                                            .on('keydown', keydown)
                                            .on('keyup', keyup);
                                    }

                                    var CI = {};
                                    window.CI = CI;

                                    $scope.ok = function() {
                                        $modalInstance.close($scope.selected_node);
                                    };

                                    $scope.cancel = function() {
                                        $modalInstance.dismiss('cancel');
                                    };
                                },
                                size: size,
                                resolve: {
                                    title: function() {
                                        return options.templateOptions.title;
                                    },
                                    Restangular: function() {
                                        return options.templateOptions.Restangular;
                                    },
                                    APIService: function() {
                                        return options.templateOptions.ApiService;
                                    },
                                    ConfigDataService: function() {
                                        return options.templateOptions.ConfigDataService;
                                    },
                                    ConfigFormService: function() {
                                        return options.templateOptions.ConfigFormService;
                                    },
                                    SweetAlert: function() {
                                        return options.templateOptions.Alert;
                                    },
                                    Toaster: function() {
                                        return options.templateOptions.toaster;
                                    }
                                }
                            });
                            modalInstance.result.then(function(selectedItem) {
                                options.value(selectedItem.name + '-' + selectedItem.uuid);
                            }, function() {
                                //console.log('Modal dismissed at: ' + new Date());
                            });
                        }
                    }
                }
            },
            controller: ['$scope', function($scope) {
                // setTimeout(function(){
                //     $scope.options.templateOptions.getWorkernumber($scope.options.templateOptions.ApiService).then(function(result){
                //         var modelData = $scope.options.templateOptions.Restangular.stripRestangular(result);
                //         if(modelData.status==200){
                //             $scope.model[$scope.options.key] = modelData.data;
                //             $scope.options.initialValue = $scope.model[$scope.options.key];
                //         }
                //     });
                // },1000);
            }]
        });
    });

appFormly.run(function(formlyConfig, $parse) {
    //formlyConfig.extras.fieldTransform=formlyConfig.extras.fieldTransform||[];
    var removeOnHideTransformer = function(fields, model) {
        return fields.map(function(field) {
            if (field.hideExpression && (!field.data || !field.data.dontRemoveOnHidden)) {
                addFieldRemoveOnHideWatcher(field);
            }
            if (field.type == "ui-title") {
                addFieldRemoveOnHideWatcher(field);
            }
            return field;
        });
    };

    formlyConfig.extras.fieldTransform = removeOnHideTransformer;

    function addFieldRemoveOnHideWatcher(field) {
        var watcher = getWatcher();
        if (field.watcher) {
            if (!angular.isArray(field.watcher)) {
                field.watcher = [field.watcher];
            }
            field.watcher.push(watcher);
        } else {
            field.watcher = watcher;
        }
    }

    function getWatcher() {
        return {
            expression: function(field) {
                return field.hide;
            },
            listener: function(field, newHide, oldHide, scope) {
                if (field.hide) {
                    if (field.templateOptions.pkey) {
                        $parse(field.templateOptions.pkey + "." + field.key).assign(scope.model, undefined);
                    } else {
                        $parse(field.key).assign(scope.model, undefined);
                    }
                }
                if (field.type == "ui-title") {
                    $parse(field.key).assign(scope.model, undefined);
                }
            }
        };
    }
});

appFormly.controller('CustomformCtrl', ['$rootScope', '$scope', '$parse', '$injector', '$http', '$q', '$state', '$stateParams', '$modal', '$timeout', '$interval', 'SweetAlert', 'FileUploader', 'i18nService', 'Restangular', 'UserRestangular', 'BpmRestangular', 'api_configure_form', 'api_bpm_domain', 'api_bpm_data', 'api_user_data',
    function($rootScope, $scope, $parse, $injector, $http, $q, $state, $stateParams, $modal, $timeout, $interval, SweetAlert, FileUploader, i18nService, Restangular, UserRestangular, BpmRestangular, api_configure_form, api_bpm_domain, api_bpm_data, api_user_data) {
        //console.log($parse('Restangular')($scope));
        //console.log($injector.get('Restangular'));
        //console.log($stateParams);



        var vm = this;
        vm.options = {};
        vm.exampleTitle = ['expressionProperties', 'model property'];
        vm.fields = [];
        vm.model = {};

        $scope.langs = i18nService.getAllLangs();
        $scope.lang = 'zh-cn';
        i18nService.setCurrentLang($scope.lang);
        //alert($rootScope.user.id,null,2);
        vm.model["loginUser"] = $rootScope.user;
        var that = $injector;
        var parse = $parse;

        var formKey = "";
        var pdKey = "";
        var modelWatch = "";
        if (angular.isDefined($stateParams.model) && $stateParams.model != "") {
            modelWatch = JSON.parse($stateParams.model);

            // console.log("modelWatch:"+ JSON.stringify(modelWatch));
        }
        if (angular.isDefined($state.current.pdKey) && $state.current.pdKey != "") {
            pdKey = $state.current.pdKey;

        }
        console.log("pdKey::" + JSON.stringify($state.current.title));
        if (angular.isDefined($stateParams.formKey) && $stateParams.formKey != "") {
            formKey = $stateParams.formKey;
            // console.log("formKey::"+JSON.stringify($stateParams.formKey));
        }

        if (angular.isDefined($stateParams.model)) {
            var formModel = $stateParams.model;
        }
        //用户测试数据，后续从header的auth中获取
        var userId = 2;
        userId = $rootScope.user.id;

        //==============处理表单设计数据  开始====================
        //处理组件加载后台数据选项的方法
        function refreshSelectOptions(searchVal, field) {
            if (field.templateOptions.optionsUrl) {
                var process = BpmRestangular.all("");
                if (field.templateOptions.ApiService) {
                    process = UserRestangular.all("");
                }

                process.customPOST({ "idx": 0, "sum": 1000 }, field.templateOptions.optionsUrl).then(function(result) {
                    if (!field.templateOptions.options) {
                        field.templateOptions.options = [];
                    }
                    if (field.templateOptions.optionsDataKey) {
                        field.templateOptions.options = result[field.templateOptions.optionsDataKey];
                    } else {
                        field.templateOptions.options = result;
                    }
                });
            }
        }



        //解析自定义表单设计数据
        function decodeVMForm(vmForm) {
            var result = { model: {}, fields: [] };
            //设置模型实体数据 begin
            //        var mdata = vmForm.model;
            //解析数据实体
            var mdata = angular.fromJson(vmForm.model); //JSON.parse(field.extjson);
            angular.extend(result.model, mdata);

            if (modelWatch != null && modelWatch != '') {
                //angular.extend(result.model.incident,modelWatch.incident);
                //result.model.alarmType = modelWatch.alarmType;
                // vmForm.cancelUrl = modelWatch.cancelUrl;
                for (var index in modelWatch.model) {
                    //console.log(JSON.stringify(index+" " +JSON.stringify( modelWatch.model[index])));
                    if (result.model[index] != null) {
                        angular.extend(result.model[index], modelWatch.model[index]);
                    } else {
                        result.model[index] = modelWatch.model[index];
                    }
                }
            }
            //设置模型实体数据 end
            //解析设计数据生成表单项 begin
            var fields = [];
            //处理修改设计数据中展示设置
            angular.forEach(vmForm.fields, function(field) {
                if (field.key == "") {
                    delete field.key;
                }

                if (angular.isDefined(field.extjson)) {
                    var extObj = angular.fromJson(field.extjson); //JSON.parse(field.extjson);
                    angular.extend(field.templateOptions, extObj.templateOptions);
                    delete extObj.templateOptions;
                    for (var prop in extObj) {
                        if (new RegExp("Expression").test(prop)) {
                            //var obj = $scope.$eval(extObj[prop]);
                            //extObj[prop] = $scope.$eval(extObj[prop]);
                            if (extObj[prop] != null) {
                                if (new RegExp("function").test(extObj[prop])) {
                                    var propValue = eval(extObj[prop]);
                                    extObj[prop] = propValue;
                                } else {
                                    //console.log(extObj[prop]);
                                    var obj = $scope.$eval(extObj[prop]);
                                    extObj[prop] = obj;
                                    //console.log(obj);
                                }
                            }
                        } else if (new RegExp("expressionProperties").test(prop)) {
                            for (var p in extObj[prop]) {
                                if (new RegExp("function").test(extObj[prop][p])) {
                                    var propValue = eval(extObj[prop][p]);
                                    extObj[prop][p] = propValue;
                                } else {
                                    //if(p.indexOf("'")>=0){
                                    // var obj = $scope.$eval(extObj[prop][p]);
                                    // extObj[prop][$scope.$eval(p)]=obj;
                                    //}
                                }
                            }
                        } else if ("watcher" == prop) {
                            if (angular.isArray(extObj[prop])) {
                                angular.forEach(extObj[prop], function(item, index) {
                                    for (var p in item) {
                                        if (new RegExp("function").test(item[p])) {
                                            var propValue = eval(item[p]);
                                            extObj[prop][index][p] = propValue;
                                        }
                                    }
                                });
                            } else if (angular.isObject(extObj[prop])) {
                                for (var p in extObj[prop]) {
                                    if (new RegExp("function").test(extObj[prop][p])) {
                                        var propValue = eval(extObj[prop][p]);
                                        extObj[prop][p] = propValue;
                                    }
                                }
                            }
                        }
                    }
                    angular.extend(field, extObj);
                    delete field.extjson;
                }


                if (angular.isDefined(field.templateOptions)) {
                    var templateOs = field.templateOptions;
                    for (var property in templateOs) {
                        //console.log(angular.isString(templateOs[property]) +"    "+property + "    " + (!(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property]))));
                        if (angular.isString(templateOs[property])) { //&& !(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property]))
                            if (new RegExp("function").test(templateOs[property])) {
                                var propValue = eval(templateOs[property]);
                                field.templateOptions[property] = propValue;
                            } else {
                                if (that.has(templateOs[property])) {
                                    field.templateOptions[property] = that.get(templateOs[property]);
                                } else {
                                    field.templateOptions[property] = templateOs[property];
                                }
                            }
                        } else if (templateOs[property] == null) {
                            //delete field.templateOptions[property];
                        } else {}
                    }
                }
                //console.log(field);
                if (angular.isDefined(field.templateOptions) && angular.isDefined(field.templateOptions.extjson)) {
                    var extObj = angular.fromJson(field.templateOptions.extjson); //JSON.parse(field.extjson);
                    angular.extend(field.templateOptions, extObj);
                    delete field.templateOptions.extjson;
                }
                //...
                if (field.templateOptions) {
                    //处理远程获取数据控件方法调用
                    if (field.templateOptions.optionsUrl) {
                        field.templateOptions.refresh = refreshSelectOptions;
                    }
                    //事件脚本处理
                    //                if(field.templateOptions.ngChangeScript){
                    //                    if(!field.expressionProperties)field.expressionProperties={};
                    //                    field.expressionProperties.ngChange = function(modelVal,viewVal,ev){
                    ////                        console.log(ev);
                    ////                        console.log("change>>"+ev.options.key);
                    //                        eval(field.templateOptions.ngChangeScript);
                    //                    }
                    //                }
                    //                if(field.templateOptions.ngClickScript){
                    //                    if(!field.expressionProperties)field.expressionProperties={};
                    //                    field.expressionProperties.ngClick = function(modelVal,viewVal,ev){
                    ////                        console.log(ev);
                    ////                        console.log("click>>"+ev.options.key);
                    //                        eval(field.templateOptions.ngClickScript);
                    //                    }
                    //                }

                    //处理嵌套属性数据绑定/
                    if (field.templateOptions.pkey) {
                        var pmodel, i = 0;
                        angular.forEach(field.templateOptions.pkey.split("."), function(p) {
                            if (i == 0) {
                                if (result.model[p] == null) {
                                    result.model[p] = {};
                                }
                                pmodel = result.model[p];
                                i++;
                            } else {
                                if (pmodel[p] == null) {
                                    pmodel[p] = {};
                                }
                                pmodel = pmodel[p];
                            }
                        });
                        if (pmodel != null) {
                            field.model = pmodel;
                            if (pmodel[field.key] == null) {
                                pmodel[field.key] = null;
                            }
                        }
                    } else {
                        if (result.model[field.key] == null) {
                            result.model[field.key] = null;
                        }
                    }
                    //处理弹出框组件初始化
                    if (field.type == "ui-input-selectmodal") {
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-requesterselect") {
                        //field.templateOptions.language = $scope.lang;
                        field.templateOptions.modal = $modal;
                        field.templateOptions.UserService = api_user_data;
                    } else if (field.type == "ui-userselect") {
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-multiuserselect") {
                        field.templateOptions.modal = $modal;
                    } else if (field.type == "ui-search") {
                        field.templateOptions.modal = $modal;
                    } else if (field.type == "ui-modelselect") {
                        field.templateOptions.modal = $modal;
                        //console.log("$rootScope.user:" + JSON.stringify($rootScope.user));
                        field.templateOptions.loginUser = $rootScope.user;
                        //field.templateOptions.Restangular = Restangular;
                    } else if (field.type == "ui-dropfile") {
                        $scope.fileUploader = field.templateOptions.fileUploader = new FileUploader({
                            url: '/uploader'
                        });
                        field.templateOptions.taskId = $stateParams.taskId;
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        field.templateOptions.userId = $rootScope.user.id;
                        //field.ApiService=api_bpm_domain;
                    } else if (field.type == "ui-dropfilenotup") {
                        $scope.fileUploader = field.templateOptions.fileUploader = new FileUploader({
                            url: '/uploader'
                        });
                        field.templateOptions.taskId = $stateParams.taskId;
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        field.templateOptions.userId = $rootScope.user.id;
                        //field.ApiService=api_bpm_domain;
                    } else if (field.type == "ui-dropfiletable") {
                        if (field.templateOptions.processInstanceId) {

                        } else {
                            field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        }
                    } else if (field.type == "ui-repeatSection") {
                        var repeatForm = {
                            model: {

                            },
                            fields: field.templateOptions.fields
                        };
                        repeatForm.model[field.key] = [];
                        decodeVMForm(repeatForm);
                    } else if (field.type == "ui-currentuser") {
                        field.templateOptions.user = vm.model["loginUser"];
                    }
                }

                //          console.log(field);
                result.fields.push(field);
            });
            angular.extend($scope.vm.fields, result.fields);
            angular.extend($scope.vm.model, result.model);

            // console.log("$scope.vm.model="+JSON.stringify($scope.vm.model));
            vm.model["loginUser"] = $rootScope.user;
            if (modelWatch != null && modelWatch != '' && modelWatch.cancelUrl != null && modelWatch.cancelUrl != '') {
                vmForm.cancelUrl = modelWatch.cancelUrl;
            }
            $scope.formData = vmForm;
            // console.log("$scope.formData="+JSON.stringify($scope.formData.url));
            if ($scope.formData.url == "start") {
                $scope.Reset = true;
                $scope.close = false;
            } else if ($scope.formData.url == "complete") {
                $scope.Reset = false;
                $scope.close = true;
            }

            //解析设计数据生成表单项 end
            return result;
        }
        //======================处理表单设计数据  结束========================
        $scope.ldloading = {};

        function filter(obj) {
            angular.forEach(obj, function(key, value) {
                if (value === "" || value === null) {
                    delete obj[key];
                } else if (Object.prototype.toString.call(value) === '[object Object]') {
                    filter(value);
                } else if (angular.isArray(value)) {
                    angular.forEach(value, function(item) {
                        filter(item);
                    });
                }
            });
        }

        $scope.closeModel = function() {
            console.log("pdKey=" + pdKey);
            if (pdKey == "bpm_incident") {
                $rootScope.cmdbs = "incident";
                $state.go('app.incident.list', {});
            } else if (pdKey == "bpm_change") {
                $rootScope.cmdbs = "change";
                $state.go('app.change.list', {});
            } else if (pdKey == "bpm_problem") {
                $rootScope.cmdbs = "problem";
                $state.go('app.problem.list', {});
            } else if (pdKey == "bpm_release") {
                $rootScope.cmdbs = "release";
                $state.go('app.release.list', {});
            } else if (pdKey == "bpm_schedule") {
                $rootScope.cmdbs = "scheduling";
                $state.go('app.scheduling.list', {});
            } else if (pdKey == "bpm_configure") {
                $rootScope.cmdbs = "cmdb";
                $state.go('app.cmdb.plist', {});
            }
            event.preventDefault();
        };
        $scope.keyup = function(e) {
            // lastKeyDown = -1;
            if (e.keyCode === 32) {
                event.preventDefault();
            }
        }
        $scope.subable = false;
        vm.submit = function(data, style) {
            $scope.subable = true;
            $scope.ldloading[style.replace('-', '_')] = true;
            if (vm.form.$valid) {
                // $scope.ldloading[style.replace('-', '_')] = true;
                $rootScope.cmdbs = "false";
                // if($scope.ldloading[style.replace('-', '_')] == true){$scope.lng=true}
                // console.log($scope.ldloading.sm);
                // console.log("vm.options:"+ JSON.stringify(vm.options));
                vm.options.updateInitialValue();
                // console.log("dfjkasdhfkhskjf ")
                var _ = window._;
                vm.model = (function filter(obj) {
                    var dateTransKeys = [];
                    var filtered = _.pick(obj, function(v, k, obj) {
                        if (_.isDate(v)) {
                            dateTransKeys.push(k);
                        }

                        return angular.isDefined(v) && v !== null && (angular.isArray(v) ? v.length > 0 : true) && (_.isPlainObject(v) ? (!_.isEmpty(v)) : true);
                    });

                    return _.cloneDeep(filtered, function(v, index, object) {
                        if (angular.isArray(dateTransKeys) && dateTransKeys.length > 0) {
                            angular.forEach(dateTransKeys, function(item) {
                                v[item] = moment(v[item]).format('YYYY-MM-DD HH:mm:ss');

                            })
                            dateTransKey = [];
                            return v;
                        }

                        return !(_.isEmpty(filtered)) && v !== filtered && _.isPlainObject(v) ? filter(v) : undefined;
                    });
                })(vm.model);


                if (pdKey != "") {

                    if ($scope.oprcode == "save") { //保存
                        api_bpm_domain.save(taskId, vm.model).then(function(response) {
                            if (response) {
                                var resData = Restangular.stripRestangular(response);
                                SweetAlert.swal({
                                    title: "保存成功!",
                                    confirmButtonColor: "#007AFF"
                                }, function() {

                                    $state.go($scope.formData.cancelUri);
                                });
                                // if(resData.status){
                                //     resData
                                // }
                            } else {
                                SweetAlert.swal({
                                    title: "系统错误",
                                    text: "系统错误，请稍后重试!",
                                    type: "error",
                                    confirmButtonColor: "#DD6B55"
                                }, function() {
                                    $scope.subable = false;
                                });
                            }
                            $scope.ldloading[style.replace('-', '_')] = false;
                        });
                    } else {


                        switch ($scope.formData.url) {

                            case "start":
                                vm.model["initUser"] = $rootScope.user.id;
                                if (vm.model["assignee"] || vm.model["candidateGroups"]) {

                                } else {
                                    vm.model["assignee"] = $rootScope.user.id;
                                }
                                api_bpm_domain.start(pdKey, vm.model).then(function(response) {

                                    // console.log("response="+JSON.stringify(response)); 
                                    if (response) {
                                        var resData = Restangular.stripRestangular(response);
                                        if (resData) {

                                            // console.log("$scope.fileUploader="+$scope.fileUploader)
                                            if ($scope.fileUploader != null && $scope.fileUploader.getNotUploadedItems().length > 0 && resData.id) {
                                                //$scope.uploader.options.url();
                                                $scope.fileUploader.onBeforeUploadItem = function(item) {
                                                    item.url = api_bpm_domain.saveAttachments(resData.id, '00000', $rootScope.user.id).getRequestedUrl();
                                                    item.formData.push({ 'fileName': item.file.name });
                                                    //console.log();
                                                };
                                                $scope.fileUploader.uploadAll();
                                            }
                                        }

                                        SweetAlert.swal({
                                            title: "提交成功!",
                                            confirmButtonColor: "#007AFF"
                                        }, function() {
                                            $state.go($scope.formData.cancelUrl);
                                        });
                                    } else {
                                        SweetAlert.swal({
                                            title: "系统错误",
                                            text: "系统错误，请稍后重试!",
                                            type: "error",
                                            confirmButtonColor: "#DD6B55"
                                        }, function() {
                                            $scope.subable = false;
                                        });
                                    }
                                    // $scope.subable = false;
                                    $scope.ldloading[style.replace('-', '_')] = false;

                                });
                                break;
                            case "complete":
                                //                    api_bpm_domain.complete(pdKey, userId, vm.model).then(function(response){
                                //console.log("complete taskId::"+$stateParams.taskId);
                                api_bpm_domain.complete($stateParams.taskId, userId, vm.model).then(function(response) {
                                    if (response) {
                                        var resData = Restangular.stripRestangular(response);
                                        SweetAlert.swal({
                                            title: "提交成功!",
                                            confirmButtonColor: "#007AFF"
                                        }, function() {
                                            // if($scope.uploader.getNotUploadedItems().length>0&&response.data.processInstanceId){
                                            //     // $scope.uploader.options.url();
                                            //     $scope.uploader.onBeforeUploadItem = function(item) {
                                            //         item.url = api_bpm_domain.saveAttachments($stateParams.processInstanceId,$stateParams.taskId,$scope.user.id).getRequestedUrl();
                                            //         console.info('onBeforeUploadItem', item);
                                            //     };
                                            //     $scope.uploader.uploadAll();
                                            // }
                                            $state.go($scope.formData.cancelUrl);
                                        });
                                    } else {
                                        SweetAlert.swal({
                                            title: "系统错误",
                                            text: "系统错误，请稍后重试!",
                                            type: "error",
                                            confirmButtonColor: "#DD6B55"
                                        }, function() {
                                            $scope.subable = false;
                                        });
                                    }
                                    // $scope.subable = false;
                                    $scope.ldloading[style.replace('-', '_')] = false;
                                });
                                break;
                            case "back":
                                $state.go($scope.formData.cancelUrl);
                                break;
                            default:
                                $scope.subable = false;
                                $scope.ldloading[style.replace('-', '_')] = false;
                                break;
                        }
                    }
                    // var submitFunc = api_bpm_domain[$scope.formData.url]
                    // if(anuglar.isFunction(submitFunc)){
                    //     submitFunc.apply(null, pdKey)
                    // }
                }
            } else {
                if (pdKey == "bpm_incident" && data.incident.requester.account.length != 6) {
                    SweetAlert.swal({
                        title: "请求人工号格式不对",
                        text: "工号应为6位数，请重新填写！",
                        type: "error",
                        confirmButtonColor: "#DD6B55"
                    }, function() {
                        $scope.subable = false;
                    })
                } else {
                    SweetAlert.swal({
                        title: "校验错误",
                        text: "请填写必填项!",
                        type: "error",
                        confirmButtonColor: "#DD6B55"
                    }, function() {
                        $scope.subable = false;
                    });
                }
                angular.forEach(vm.form.$error.required, function(item) {
                        angular.forEach(vm.fields, function(f) {
                            if (f.name == item.$name) {
                                f.validation.show = true;
                            }
                        });
                    })
                    // $scope.subable = false;
                $scope.ldloading[style.replace('-', '_')] = false;
            }
        };

        $scope.vm = vm;

        if (angular.isDefined($stateParams.taskId) && $stateParams.taskId != "") {
            // console.log("taskId>>"+$stateParams.taskId);
            // editor process task form

            var processInstanceId = $stateParams.processInstanceId;
            api_bpm_domain.taskformkey($stateParams.taskId).then(function(response) {
                if (response) {
                    var myData = Restangular.stripRestangular(response); //console.log("myData>>>");console.log(myData);
                    api_configure_form.renderForm(myData.data, userId, processInstanceId).then(function(responseData) {
                        if (responseData) { //console.log("responseData>>>");//console.log(responseData);
                            var vmForm = Restangular.stripRestangular(responseData);
                            if (vmForm) { //console.log("vmForm>>>");//console.log(vmForm);
                                decodeVMForm(vmForm);
                                //console.log($scope);
                            }
                        }
                    });
                }
            })
        } else {

            // create process instance
            if (pdKey != "") { //for process
                api_bpm_domain.startformkey(pdKey).then(function(response) {
                    if (response) {
                        var myData = Restangular.stripRestangular(response);
                        //myData.data = "arrangeform";
                        api_configure_form.renderForm(myData.data, userId).then(function(responseData) {

                            if (responseData) {
                                var vmForm = Restangular.stripRestangular(responseData);
                                if (vmForm) {
                                    console.log('vmForm info:');
                                    console.log(vmForm);

                                    decodeVMForm(vmForm);

                                    $("#formly_1_ui-datepicker_acceptDate_4").val('1212');

                                }
                            }
                        });
                    }
                });
            } else { //for form
                //TODO
                //测试数据 开始
                var testJson = {
                    fields: [{
                            key: 'formtitle',
                            type: 'ui-title',
                            noFormControl: true,
                            templateOptions: {
                                label: 'title is ',
                                placeholder: 'Formly is terrific!'
                            }
                        },
                        // {
                        //     key:'a',type:'ui-input',className:'col-xs-4',
                        //     templateOptions: {
                        //         type: 'input',label: 'input a',placeholder:'search a...',
                        //         lBtn:{
                        //             label:'input',
                        //             onClick: function(val,opt,el,ev,model){alert(val);}
                        //         },
                        //         rAddon:'@111.cc'
                        //     }
                        // },
                        {
                            key: 'b',
                            type: 'ui-input',
                            className: 'col-xs-4',
                            templateOptions: {
                                type: 'input',
                                label: 'input a',
                                placeholder: 'search a...',
                                rBtn: {
                                    icon: 'fa fa-phone',
                                    onClick: function(val, opt, el, ev, model) { alert(val); }
                                },
                                lAddon: '<i class="fa fa-phone"/>'
                            }
                        },
                        // {
                        //     key:'first',type:'ui-input',className:'col-xs-2',
                        //     templateOptions: {
                        //         type: 'input',
                        //         label: 'first name',
                        //         pkey:'name'
                        //     }
                        // },                    
                        // {
                        //     key:'first',type:'ui-number',className:'col-xs-3',
                        //     templateOptions: {
                        //         label: '时长',
                        //         pkey:'name',
                        //         min:0,
                        //         rAddon:'分钟'
                        //     }
                        // },
                        // {
                        //     key:'last',type:'ui-input',className:'col-xs-2',
                        //     templateOptions: {type: 'input',label: 'last name',pkey:'name'}},
                        //     {
                        //         key:'username',
                        //         type:'ui-input',
                        //         className:'col-xs-4',
                        //         templateOptions: {
                        //             type: 'input',
                        //             label: 'User Name',
                        //             placeholder: 'Enter name',
                        //             required:true,
                        //             maxLength:10
                        //     }
                        // },
                        // {
                        //     key: 'password',
                        //     type: 'ui-input',
                        //     className:'col-xs-4',
                        //     templateOptions: {
                        //         type: 'password',
                        //         label: 'Password',
                        //         placeholder: 'Password',
                        //         required:true
                        //     },
                        //     expressionProperties: {
                        //         'templateOptions.disabled': '!model.username'
                        //     }
                        // },
                        // {
                        //     key: 'selectmodal',
                        //     type: 'ui-input-selectmodal',
                        //     className:'col-xs-6',
                        //     templateOptions:{
                        //         label: 'selectmodal',
                        //         btnLabel:'search',
                        //         btnClassName:'btn-o',
                        //         modalParam:{
                        //             items:  function(){
                        //                 return ['a','b','c','d'];
                        //             },
                        //             title: function(){
                        //                 return '测试标题';
                        //             }
                        //         }
                        //     }
                        // },
                        // {
                        //     key: 'email',
                        //     type: 'ui-input',
                        //     className:'col-xs-6',
                        //     templateOptions:{
                        //         type: 'email',
                        //         maxlength: 10,
                        //         minlength: 6,
                        //         label: 'EMail'
                        //     }
                        // },
                        // {
                        //     key: 'date',
                        //     type: 'ui-datepicker',
                        //     className:'col-xs-6',
                        //     templateOptions: {
                        //         label: 'Date',
                        //         type: 'text',
                        //         datepickerPopup: 'yyyy-MM-dd hh:mm:ss',
                        //         initDate : function(){
                        //             return new Date();
                        //         }

                        //     }
                        // },
                        {
                            key: 'multiselectItem',
                            type: 'ui-multi-select-tree',
                            className: 'col-xs-6',
                            templateOptions: {
                                label: 'multiSelect',
                                placeholder: '请选择...',
                                isMultiSelect: false,
                                selLeafs: false, //只选叶子节点
                                refreshData: function(APIService) {
                                    return APIService.fetchDataList('changeclassify', { 'idx': 0, 'sum': 100 });
                                },
                                APIService: api_bpm_data,
                                optionsDataKey: 'list',
                                refreshDelay: 1000,
                                onDataCallback: function(item, selectItems, options, field, model) {
                                    model[options.key] = { id: item.id };
                                    // console.log("item="+JSON.stringify(model))
                                }
                            }
                        },
                        // {
                        //     key:'selectItem',
                        //     type:'ui-select',
                        //     className:'col-xs-4',
                        //     templateOptions:{
                        //         label:'ui-select',
                        //         valueProp: 'code',//对应value
                        //         labelProp: 'source',//对应key
                        //         optionsUrl:'data/fetchDataList/incidentsource',//对应后台地址，api/之前的部分省略
                        //         optionsDataKey:'list',//对应返回数组数据的键值,
                        //         required:true,
                        //         onChange:function(val, options, field, event ,model){
                        //             model.start_code = val;
                        //         }
                        //     }
                        // },
                        // {
                        //     key:'id',
                        //     type:'ui-multiselect',
                        //     className:'col-xs-4',
                        //     templateOptions:{
                        //         label:'multi-select',
                        //         pkey:"change.systemType",
                        //         valueProp: 'id',//对应value
                        //         labelProp: 'source',//对应key
                        //         optionsUrl:'data/fetchDataList/changesystemtype',//对应后台地址，api/之前的部分省略
                        //         optionsDataKey:'list',//对应返回数组数据的键值,
                        //         required:true,
                        //         onChange:function(val, options, field, event ,model){
                        //             console.log(val);
                        //             console.log(model);
                        //             //model.start_code = val;
                        //         }
                        //     }
                        // },
                        {
                            key: 'checklistItem',
                            type: 'ui-checklist',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: 'checklistItem',
                                options: [
                                    { name: 'Iron Man', value: 'iron_man' },
                                    { name: 'Captain America', value: 'captain_america' },
                                    { name: 'Black Widow', value: 'black_widow' },
                                    { name: 'Hulk', value: 'hulk' },
                                    { name: 'Captain Marvel', value: 'captain_marvel' }
                                ]
                            }
                        },
                        {
                            key: 'radioItem',
                            type: 'ui-radio',
                            className: 'col-xs-8',
                            templateOptions: {
                                label: 'radioItem',
                                options: [
                                    { name: 'Iron Man', value: 'iron_man' },
                                    { name: 'Captain America', value: 'captain_america' },
                                    { name: 'Black Widow', value: 'black_widow' },
                                    { name: 'Hulk', value: 'hulk' },
                                    { name: 'Captain Marvel', value: 'captain_marvel' }
                                ],
                                type: 'number'
                            }
                        },
                        // {
                        //     key:'selectUser',
                        //     type:'ui-userselect',
                        //     className:'col-xs-12',
                        //     templateOptions:{
                        //         label:'请求人信息',
                        //         modalTitle:'请求人列表',
                        //         fetchItems:function(filterData, APIService){
                        //             return APIService.fetchDataList('user',filterData);
                        //         },
                        //         Restangular:Restangular,
                        //         ApiService:api_user_data,
                        //         onClick:function(val, options, field, event , model){
                        //             //model.start_code++;
                        //             console.log(options);
                        //         }
                        //     }
                        // },
                        {
                            key: 'selectUser',
                            type: 'ui-requesterselect',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: '请求人信息',
                                modalTitle: '请求人列表',
                                fetchItems: function(filterData, APIService) {
                                    return APIService.fetchDataList('requester', filterData);
                                },
                                Restangular: Restangular,
                                ApiService: api_user_data
                                    // onClick:function(val, options, field, event , model){
                                    //     console.log(options);
                                    // }
                            }
                        },
                        {
                            key: 'cabUser',
                            type: 'ui-multiuserselect',
                            className: 'col-xs-12',
                            templateOptions: {
                                label: 'CAB评审成员',
                                modalTitle: 'CAB成员列表',
                                fetchItems: function(filterData, APIService) {
                                    return APIService.fetchDataList('user', filterData);
                                },
                                Restangular: Restangular,
                                ApiService: api_user_data,
                                onClick: function(val, options, field, event, model) {
                                    // console.log(model);
                                }
                            }
                        },
                        // {
                        //     key:'incident',
                        //     type:'ui-modelselect',
                        //     className:'col-xs-3',
                        //     templateOptions:{
                        //         label:'关联事件工单',
                        //         modalTitle:'事件列表',
                        //         fetchItems:function(filterData,APIService){
                        //             return APIService.fetchDataList('incident',filterData);
                        //         },
                        //         Restangular:"Restangular",
                        //         ApiService:"api_bpm_data",
                        //         columnDefs:[
                        //                     { name:'id', width:80, enableFiltering:false},
                        //                     { name:'title', displayName:'事件主题', width:140},
                        //                     { name:'type.name', displayName:'事件类型', width:140},
                        //                     { name:'emergency.name', displayName:'紧急度', width:80},
                        //                     { name:'state.name', displayName:'状态', width:100},
                        //                     { name:'emergency.name', displayName:'紧急度', width:80},
                        //                     { name:'influence.name', displayName:'影响度', width:80},
                        //                     { name:'priority.name', displayName:'优先级', width:80},
                        //                     { name:'handlerUser.name', displayName:'当前处理人', width:100},
                        //                     { name:'acceptDate', displayName:'创建时间', width:100}                                        
                        //         ],
                        //         displayName:'title', 
                        //         onClick:function(val, options, field, event , model){
                        //             //model.start_code++;
                        //             console.log(options);
                        //         }
                        //     }
                        // },
                        // {
                        //     key: 'worknumber',
                        //     type: 'ui-workernumber',
                        //     className:'col-xs-3',
                        //     templateOptions: {
                        //         label: 'work number',
                        //         Restangular:Restangular,
                        //         ApiService:api_bpm_domain,
                        //         getWorkernumber: function(APIService){
                        //             return APIService.workernumber('bg');
                        //         }
                        //     }
                        // },
                        // {
                        //     key: 'chkme',
                        //     type: 'ui-checkbox',
                        //     className:'col-xs-3',
                        //     templateOptions: {
                        //         label: 'Check me out'
                        //     }
                        // },
                        // {
                        //     key: 'droplink',
                        //     type: 'ui-link',
                        //     className: 'col-xs-3',
                        //     templateOptions:{
                        //         label:'添加附件',
                        //         onClick:function(val, options, field, event ,model){
                        //             if(angular.isUndefined(field.form.dropState)){
                        //                 field.form.dropState=false;
                        //             }
                        //             field.form.dropState=!field.form.dropState;  
                        //             console.log(field);
                        //         }
                        //     }
                        // },
                        // {
                        //     key: 'dropfile',
                        //     type: 'ui-dropfile',
                        //     className: 'col-xs-12',
                        //     templateOptions:{
                        //         label:'附件',
                        //         uploadUrl:'http://127.0.0.1:9008/saveAttachments'
                        //     }
                        // },
                        // {
                        //     type: 'ui-label',
                        //     key: 'changesign',
                        //     className: 'col-xs-4',
                        //     templateOptions: {
                        //         label:'变更请求单号',
                        //         pkey:'change'
                        //     }
                        // },
                        // {   
                        //     type: 'ui-label',
                        //     key: 'title',
                        //     className: 'col-xs-4',
                        //     templateOptions: {
                        //         label:'变更标题',
                        //         pkey:'change'
                        //     }
                        // },
                        // //关联发布单号
                        // //新建发布                    
                        // {
                        //     key: 'droplist',
                        //     type: 'ui-dropfiletable',
                        //     className: 'col-xs-12',
                        //     templateOptions:{
                        //         label:'附件下载列表',
                        //         Restangular:Restangular,
                        //         processInstanceId:'250033',
                        //         ApiService:api_bpm_domain
                        //     }
                        // },
                        // {
                        //     type: 'ui-repeatSection',
                        //     key: 'investments',
                        //     className: 'col-xs-12',
                        //     templateOptions: {
                        //         btnText: '新增变更施工单',
                        //         fields: [
                        //             {
                        //                 className: 'col-xs-3',
                        //                 type: 'ui-input',
                        //                 key: 'aboutci',
                        //                 templateOptions: {
                        //                     label: '关联的配置项',
                        //                     required: true
                        //                 }
                        //             },
                        //             {
                        //                 className: 'col-xs-3',
                        //                 type: 'ui-datepicker',
                        //                 key: 'planbegintime',
                        //                 templateOptions: {
                        //                     label: '计划开始时间',
                        //                     required: true
                        //                 }
                        //             },   
                        //             {
                        //                 className: 'col-xs-3',
                        //                 type: 'ui-datepicker',
                        //                 key: 'planendtime',
                        //                 templateOptions: {
                        //                     label: '计划完成时间',
                        //                     required: true
                        //                 }
                        //             },
                        //             {
                        //                 className: 'col-xs-12',
                        //                 type: 'ui-userselect',
                        //                 key: 'handleruser',
                        //                 templateOptions: {
                        //                     label: '实施人员信息',
                        //                     modalTitle:'实施人列表',
                        //                     required: true,
                        //                     fetchItems:function(filterData, APIService){
                        //                         return APIService.fetchDataList('user',filterData);
                        //                     },
                        //                     Restangular:Restangular,
                        //                     ApiService:api_user_data,
                        //                     onClick:function(val, options, field, event , model){
                        //                         //model.start_code++;
                        //                         console.log(options);
                        //                     }
                        //                 }
                        //             },
                        //             {
                        //                 className: 'col-xs-8',
                        //                 type: 'ui-textarea',
                        //                 key: 'handlerContent',
                        //                 templateOptions: {
                        //                     label: '实施内容',
                        //                     required: true,
                        //                     row:10
                        //                 }
                        //             },{
                        //                 noFormControl: true,
                        //                 template:'<hr>'
                        //             }]
                        //     }
                        // },
                        // {
                        //     key: 'droplist',
                        //     type: 'ui-dropfiletable',
                        //     className: 'col-xs-12',
                        //     templateOptions:{
                        //         label:'附件下载列表',
                        //         Restangular:Restangular,
                        //         processInstanceId:'250033',
                        //         ApiService:api_bpm_domain
                        //     }

                        // },
                        // {
                        //     key: 'start_code',
                        //     className:'col-xs-6',
                        //     type: 'ui-hidden'
                        // },
                        // {
                        //     key:'remark',
                        //     type:'ui-textarea',
                        //     className:'col-xs-12',
                        //     templateOptions:{
                        //         label:'remark is ',
                        //         rows:3
                        //     }
                        // },
                        {
                            key: 'setStartCode',
                            type: 'ui-button',
                            className: 'col-xs-4',
                            templateOptions: {
                                label: '升级为变更',
                                onClick: function(val, options, field, event, model) {
                                    //console.log(options);
                                    event.preventDefault();
                                    //model.start_code++;
                                    //console.log(options);
                                }
                            }
                        }
                    ],
                    model: {
                        username: "robin lau",
                        password: "123456",
                        chkme: false,
                        start_code: 0,
                        formtitle: "Hey!I am title value!",
                        name: {
                            first: "robin",
                            last: "lau"
                        },
                        multiselectItem: []
                            //date:"2015-09-15 00:00:00"
                    }
                };
                setTimeout(function() {
                    decodeVMForm(testJson);
                    $scope.$apply();
                }, 500);
                //测试数据结束
            }
        }
        //console.log("end decode");
    }
]);